简体   繁体   中英

Updating child property from parent in React Native

I want to be able to update a child component property from both the parent and itself according to the last event.

For example:

class MyParent extends Component {
  state ={
    text:"";
  }
  render() {
    return (
      <View>
        <MyChild text={this.state.text} />
        <Button
          onPress={()=>this.setState({text:"parent"})}
          title="Update From Parent"
        />
     </View>
   );
  }
} 


class MyChild extends Component {
    state ={
      text:"";
    }

    componentWillReceiveProps(nextProps) {
    if (nextProps.text!== this.state.text) {
       this.setState({text:nextProps.text});
    }
}

render() {
    return (
      <View>
        {/* I want that the text field will be updated from the last event*/}
        <Text>{this.state.text}</Text>
        <Button
            onPress={()=>this.setState({text:"child"})}
            title="Update From Child"
        />
      </View>
   );
  }
} 

The issue is that componentWillReceiveProps is triggered each time the setState is called so the text property takes the value from the parent and not from the child.

How can I achive this result?

Thanks a lot Elad

Manage your state through parent component and pass the function that will update the state of parent component in child component

class MyParent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      text: "",
      updateParentState: (newState) => this.setState(newState)
    }
  }

  render() {
    let { text, updateParentState } = this.state;
    return (
      <View>
        <MyChild data={{ text, updateParentState }} />
        <Button
          onPress={() => updateParentState({ text: "parent" })}
          title="Update From Parent"
        />
      </View>
    );
  }
}


class MyChild extends Component {

  constructor(props) {
    super(props);
    this.state = {
      text: props.data.text
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.text !== this.state.text) {
      this.setState({ text: nextProps.data.text });
    }
  }

  render() {
    let { updateParentState } = this.props.data;
    return (
      <View>
        <Text>{this.state.text}</Text>
        <Button
          onPress={() => updateParentState({ text: "child" })}
          title="Update From Child"
        />
      </View>
    );
  }
}

You are missing this. in the setState call in child. please check if this is not the issue.

<Button
  onPress={()=>setState({text:"child"})}
  title="Update From Child"
/>

should be

<Button
  onPress={()=>this.setState({text:"child"})}
  title="Update From Child"
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM