我正在创建一个示例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>
组件中所做的选择?
这是<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>
设计错误吗?
答案 0 :(得分:1)
我在这里想念的是什么?我的设计错了吗?
好吧,如果您“提升状态”单选按钮本身根本不应该具有任何状态。而是将处理程序传递给RadioButton:
<RadioButton onChange={value => this.doSomethingWith(value)} />
然后,每当更改了某些内容时,您都可以在单选按钮中调用该名称,并在<App/>
中处理结果。
如果您必须将该处理程序向下传递多个级别,则最好使用context。