1

我正在为学习目的创建一个示例反应应用程序,因为我遵循了单独组件的层次结构:

<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>错了吗?

4

1 回答 1

1

我在这里缺少什么?难道我的设计错了?

好吧,如果您“提升状态”,单选按钮本身根本不应该有任何状态。而是将处理程序传递给 RadioButton:

 <RadioButton onChange={value => this.doSomethingWith(value)} />

然后,您可以在更改某些内容时在单选按钮内部调用它,并以<App/>.

如果您必须通过多个级别传递该处理程序,则使用context可能会更好。

于 2019-01-01T11:50:26.810 回答