[英]Passing props in React Native
我有這個組成部分:
<View style={{backgroundColor: solved === true ? 'green' : '#ff5b68'}}>
<Text>{error}</Text>
<Text>{errorInfo}</Text>
<Text>{key}</Text>
<Text>{uid}</Text>
<MarkedAsSolvedButton key={key}/>
</View>
我想將密鑰傳遞給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}/>
);
}
}
但是,當我嘗試查看該密鑰時,它顯示為undefined
。 但這給了我父級組件中的值。
我想念什么?
key
是react中的一個非常特殊的道具,它故意不暴露給子組件。 它是一種提供對其他信息的反應的方式,可以用來優化性能,尤其是在處理列表時(請參閱本頁 )。 如果您需要將信息公開給孩子,則需要將其作為其他道具傳遞(可以是關鍵道具的補充,也可以代替它)。 例如:
// In the parent component's render:
<MarkAsSolvedButton key={key} identifier={key} />
// in MarkAsSolved:
handlePress = () => {
alert(this.props.identifier);
}
onPressButton(){}
render() {
return (
<ChildrenComponent
name={"testing to props"}
onFunction={this.onPressButton.bind(this)}
key={this.state.key}
/>
);
}
和兒童部分
<View>
<Button onPress={()=>this.props.onFunction(this.props.key)}>
<Text>{this.props.name}</Text>
</Button>
</View>
您可以在渲染后將類似道具與其他道具一起使用
添加帶有道具的構造函數:
constructor(props) {
super(props)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.