我正在为学习目的创建一个示例反应应用程序,因为我遵循了单独组件的层次结构:
<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>
现在,当我按下按钮时,我想通过在单选按钮中传递所选选项来导航到其他屏幕。
我读过这篇关于提升状态的文章。但问题是,这里没有我可以将状态提升到的共同父祖先。
如果我将状态列出到<HomeScreen>
组件,我该如何管理<RadioButton>
组件中的选择?
这是<RadioButton>
组件的完整代码:
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
)。
我在这里缺少什么?我的设计<RadioButton>
错了吗?