How to update parent's state in React?

后端 未结 14 1623
粉色の甜心
粉色の甜心 2020-11-22 08:48

My structure looks as follows:

Component 1  

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5  

Component 3

Component 3 s

14条回答
  •  独厮守ぢ
    2020-11-22 09:27

    For child-parent communication you should pass a function setting the state from parent to child, like this

    class Parent extends React.Component {
      constructor(props) {
        super(props)
    
        this.handler = this.handler.bind(this)
      }
    
      handler() {
        this.setState({
          someVar: 'some value'
        })
      }
    
      render() {
        return 
      }
    }
    
    class Child extends React.Component {
      render() {
        return 

    This way the child can update the parent's state with the call of a function passed with props.

    But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.

    One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.

提交回复
热议问题