我有这个组件:
<View style={{backgroundColor: solved === true ? 'green' : '#ff5b68'}}>
<Text>{error}</Text>
<Text>{errorInfo}</Text>
<Text>{key}</Text>
<Text>{uid}</Text>
<MarkedAsSolvedButton key={key}/>
</View>
我想将 key 传递给 MarkedAsSolvedButton
组件。代码如下:
export default class MarkedAsSolvedButton extends React.Component {
componentWillReceiveProps(nextProps) {
alert(nextProps.key)
}
handlePress = () => {
alert(this.props.key);
};
render() {
return (
<Button onPress={this.handlePress} title={'Marked as solved' + this.props.key}/>
);
}
}
但是当我尝试查看 key 时,它显示 undefined
。但它给了我父组件中的值。
我错过了什么?
最佳答案
key
是 react 中一个非常特殊的 prop,它有意不暴露给子组件。它作为一种提供 react 的方式而存在,它可以使用可用于优化性能的附加信息,尤其是在处理列表时(参见 this page )。如果您需要将信息公开给 child ,则需要将其作为不同的 Prop 传递(这可以是关键 Prop 的补充,也可以代替它)。例如:
// In the parent component's render:
<MarkAsSolvedButton key={key} identifier={key} />
// in MarkAsSolved:
handlePress = () => {
alert(this.props.identifier);
}
关于javascript - 在 React Native 中传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54712519/