如何在React Native中为props设置默认值

时间:2020-03-11 17:45:47

标签: javascript react-native jsx react-props

我需要知道如何为React Native的prop设置默认值。 我有以下代码:

<View style={{ ...styles.textBox, ...props.bg }}>
    <Text style={{ ...styles.pretitle, ...props.style }}>{props.pretitle}</Text>
    <Text style={{ ...styles.title, ...props.style2 }}>{props.title}</Text>
    <Text style={styles.introduction}>{{ '', ...props.introduction }}</Text>
</View>

如果props.introduction0,我想将其设置为空,例如:”,或设置其他值,例如:“未设置”。

谢谢

1 个答案:

答案 0 :(得分:4)

您可以在React中使用defaultProps

export default class Example extends React.Component {
  render() {
    return (
      <View>
        <Text>{this.props.fName},{this.props.lName}</Text>
      </View>
    );
  }
}


Example.defaultProps = {
    fName: "Hello",
    lName: 'world'
}

希望这对您有所帮助。放心怀疑。