【问题标题】:React-native const component doesn't receive props?React-native const 组件不接收道具?
【发布时间】:2018-05-23 00:13:34
【问题描述】:

来自 React,我认为传递 props 是一样的,显然不是?

我有一个登录表单,我想在其中登录,并使用不同样式的注册按钮。

在我的登录表单中,我有以下方法:

   renderButton (type, text) {
        if (this.state.loading) {
            return <Spinner size="small" />;
        }

        let btnColors = {
            bgColor: colors.whiteText,
            textColor: colors.primaryTeal
        };

        if (type === "signUp") {
            btnColors.bgColor = colors.whiteText;
            btnColors.textColor =  colors.primaryTeal;

        } else if (type === "logIn") {
            btnColors.bgColor = colors.darkTeal;
            btnColors.textColor = colors.whiteText;
        }
        return (
            <Button colors={btnColors} onPress={this.onButtonPress.bind(this)}>
                {text}
            </Button>
        );
    }

在渲染中调用:

{this.renderButton("signUp", "SIGN UP")}

Button.js 看起来像:

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


const Button = ({colors, onPress, children }) => {

    const styles =  StyleSheet.create({
        textStyle: {
            alignSelf: 'center',
            color: colors.textColor,
            fontSize: 16,
            fontWeight: '900',
            paddingTop: 10,
            paddingBottom: 10,
        },
        buttonStyle: {
            flex: 1,
            backgroundColor: colors.bgColor,
            borderRadius: 50
        },
    });

      return (
            <TouchableOpacity onPress={onPress} style={styles.buttonStyle}>
              <Text style={styles.textStyle}>
                  {children}
              </Text>
            </TouchableOpacity>
      );
};


export { Button };

出现错误:

undefined is not an object (evaluating 'colors.textColor')

为什么它不起作用,我如何有条件地将道具作为对象传递以用于样式设置?

【问题讨论】:

  • 不应该&lt;Button colors={colors}...&lt;Button colors={btnColors}...
  • 正确,它是,改变它 - 错误是一样的,虽然

标签: javascript react-native react-props


【解决方案1】:

尝试将组件更改为类组件而不是功能组件,这应该可以解决问题...alternatove ypu 可以使用如下所示的粗箭头语法:

const HelloWorld = ({name}) => ( <div>{`Hi ${name}`}</div>);

【讨论】:

    猜你喜欢
    • 2021-03-09
    • 2018-01-10
    • 2016-08-08
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 2020-09-15
    • 2019-04-25
    相关资源
    最近更新 更多