我正在创建一个用于学习目的的示例React应用程序,其中我遵循独立组件的层次结构:
<RadioButton>
//Radio buttons are rendered here and selection of radio buttons are maintained in state of this component
</RadioButton>
<SelectCard>
<RadioButton dataToPopulate = ['choice A', 'choice B'] />
</SelectCard>
<ParentSelectCard>
<SelectCard /> //Rendering SelectCard with passing some data as prop from here
</ParentSelectCard>
<Button /> //Custom button component
<HomeScreen>
<ParentSelectCard />
<Button />
</HomeScreen>
现在,当我按下按钮时,我想通过在单选按钮中传递所选选项来导航到其他屏幕。
我读过
this article about lifting state up.
但问题是,这里没有一个共同的父母祖先,我可以把国家提升到这个水平。
如果我把州列为
<HomeScreen>
组件,如何管理在
<RadioButton>
组件?
这是完整的代码
<ReloButt & GT;
组件:
class RadioButton extends React.Component {
constructor(props) {
super(props);
this.state = {
radioSelected: 0
}
}
handleRadioClick(id) {
this.setState({
radioSelected: id
});
}
render(){
return this.props.dataToPopulate.map((element) => {
return (
<View key = {element.id} style={styles.radioButton}>
<TouchableOpacity style={styles.radioButtonTint} onPress = {this.handleRadioClick.bind(this, element.id)}>
{ element.id === this.state.radioSelected ? (<View style={styles.radioButtonSelected}/>) : (null) }
</TouchableOpacity>
<Text style={styles.radioButtonText}> {element.value} </Text>
</View>
);
});
}
}
在这里,您可以看到所做的最终选择将存储在此组件的状态中(在
radioSelected
)
我错过了什么?是我的设计
<ReloButt & GT;
错了?