React Native 可重用卡片组件不会按预期显示

React Native Reusable Card Component won't Visualize as expected

你好,我是 React Native 新手。我正在尝试创建可重用组件,而不仅仅是卡片组件,也许将来会创建其他可重用组件。下面是我创建的可重用卡片组件的代码示例:

Card.js

import React from 'react';
import { View, StyleSheet } from 'react-native';
const Card = props => {
return (
<View  style={{...styles.card, ...props.style}}>{props.children}</View>);};

const styles = StyleSheet.create({
 card: {
   shadowColor: 'black',
   shadowOffset: { width: 0, height: 2 },
   shadowRadius: 6,
   shadowOpacity: 0.26,
   elevation: 8,
   backgroundColor: 'white',
   padding: 20,
   borderRadius: 10,

     }
   });

 export default Card;

StartGameScreen.js

import React from 'react';
import { View, Text, StyleSheet, TextInput, Button } from 'react-native';

import Card from '../components/Card';

  const StartGameScreen = props => {
    return (
     <View style={styles.screen}>
       <Text style={styles.title}>Start a New Game!</Text>
        <Card style={styles.inputContainer}>
          <Text>Select a Number</Text>
          <TextInput />
          <View style={styles.buttonContainer}>
            <View style={styles.button}><Button title="Reset" onPress={() => {}} /></View>
            <View style={styles.button}><Button title="Confirm" onPress={() => {}} /></View>
          </View>
         </Card>
     </View>
   );
 };

 const styles = StyleSheet.create({
  screen: {
    flex: 1,
    padding: 10,
    alignItems: 'center'
    },
  title: {
    fontSize: 20,
    marginVertical: 10
    },
  inputContainer: {

    width: 300,
    maxWidth: '80%',
    alignItems: 'center'

    },

  buttonContainer: {
    flexDirection: 'row',
    width: '100%',
    justifyContent: 'space-between',
    paddingHorizontal: 15
      },
  button: {
    width:100
     }
   });

export default StartGameScreen;

结果如下:

我希望它如下所示:

是否可以使用我上面的代码并得到预期的结果?还是我的代码有误,有更好的解决办法??

您的卡片组件是可重用的,唯一的错误是您合并样式的方式。当你合并样式时,你不应该扩展它,而是使用一个样式数组。如下所示。

const Card = props => {
  return (<View style={[styles.card, props.style]}>{props.children}</View>);
};

您可以查看以下小吃以获取完整代码。 https://snack.expo.io/@guruparan/e368b9