代码之家  ›  专栏  ›  技术社区  ›  Kaushal28

在react native中提升状态时卡住

  •  1
  • Kaushal28  · 技术社区  · 6 年前

    我正在创建一个用于学习目的的示例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; 错了?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Jonas Wilms    6 年前

    我错过了什么?我的设计错了吗?

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

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

    然后,您可以在任何事情发生变化时调用单选按钮的内部,并在 <App/> .

    如果必须通过多个级别传递该处理程序,则最好使用 context .