javascript - React-native const 组件没有接收 props?

标签 javascript react-native react-props

来自 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 不是对象(正在计算“colors.textColor”)

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

最佳答案

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

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

关于javascript - React-native const 组件没有接收 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47719609/

相关文章:

javascript - 缩小宽度时如何调整高度?

javascript - Put Request、JQuery、MongoDB 和 Mongoose 的更新问题

react-native - SectionList : props.sections.reduce 不是一个函数

react-native - 运行react-native run android时无法识别Tterm 'react-native'

javascript - 如何使用 return() 中定义的参数调用 render() 中的函数

javascript - 即使未显式使用 `componentWillMount`,'componentWillMount' 警告仍可见

javascript - Bootstrap Modal和YouTube Player技巧

javascript - 切换 Angular css 类

android - 为 react-native native android 方法编写单元测试

javascript - 如何仅在收到 props 时渲染 React(使用 Redux)组件?