【问题标题】:Style is not passed down to Custom Component React Native样式未传递给自定义组件 React Native
【发布时间】:2018-05-13 02:08:58
【问题描述】:

我有一个带有此代码的自定义按钮组件

import React from 'react';
import { TouchableOpacity, View, Text } from 'react-native';
import PropTypes from 'prop-types';

import styles from './styles';

const CustomBtn = ({props, text, onPress }) => (
    <TouchableOpacity {...props} onPress={onPress}>
        <View style={styles.button}>
             <Text style={styles.text}>{text}</Text>
        </View>
    </TouchableOpacity>
);

CustomBtn = {
  text: PropTypes.string,
  onPress: PropTypes.func,
};

export default CustomBtn;

我想在我编写的视图中覆盖组件的样式(边距、填充)

<CustomBtn style={styles.BtnMargin} onPress={this.handlePressLogin} text="Login" />

但是我的自定义按钮没有得到样式。如何更改自定义btn的代码来解决这个问题?

【问题讨论】:

    标签: javascript reactjs react-native components


    【解决方案1】:

    您使用的stateless component 错误。如果您查看签名,您会注意到它接受道具作为参数:

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    

    {...props} 行中,变量props 未定义,因为它与普通组件中的this.props.props 相同。你真正想做的是:

    const CustomBtn = (props) => (
        <TouchableOpacity {...props} onPress={props.onPress}>
            <View style={styles.button}>
                 <Text style={styles.text}>{props.text}</Text>
            </View>
        </TouchableOpacity>
    );
    

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 2016-08-05
      • 2016-09-25
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多