React Native 可重用卡片组件不会按预期进行可视化 [英] React Native Reusable Card Component won't Visualize as expected

本文介绍了React Native 可重用卡片组件不会按预期进行可视化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我是本机反应的新手.我正在尝试创建可重用组件,不仅是卡片组件,将来可能还会创建其他可重用组件.下面是我创建的可重用卡片组件的代码示例:

Hello there I'm new to react native. I'm trying to create reusable component, not only card component, maybe in future will create other reusable components. Below is the code example of reusable card component that I've created:

卡片.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

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;

结果如下:

我希望它如下所示:

是否可以使用我上面的代码并获得预期的结果?还是我的代码错了,有更好的解决方案?

推荐答案

你的卡片组件是可重用的,唯一的错误是你合并样式的方式.合并样式时,不应展开它,而应使用样式数组.如下图.

Your card component is reusable only mistake is the way you are merging the styles. When you merge styles you should not expand it but use an array of styles. Like below.

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

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

You can check the below snack for full code. https://snack.expo.io/@guruparan/e368b9

这篇关于React Native 可重用卡片组件不会按预期进行可视化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆