【发布时间】:2019-01-01 11:40:30
【问题描述】:
我正在创建一个示例反应应用程序以用于学习目的,因为我遵循了不同组件的层次结构:
<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>设计错了吗?
【问题讨论】:
-
就个人而言,我会选择 redux 或 mobx 或其他状态管理库来存储全局状态。
-
所以 redux 是用于将状态存储到某个全局变量,然后从任何地方访问它,对吗?我是 React/Redux 的新手。
-
是的,没错。通常你会有容器组件来访问 redux 存储并选择状态的特定部分,然后将其传递给 ui 组件。本课程是免费的,可能会帮助您入门:egghead.io/courses/getting-started-with-redux
标签: javascript reactjs react-native ecmascript-6 react-state-management