How to update parent's state in React?

后端 未结 14 1379
粉色の甜心
粉色の甜心 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:41

    When ever you require to communicate between child to parent at any level down, then it's better to make use of context. In parent component define the context that can be invoked by the child such as

    In parent component in your case component 3

    static childContextTypes = {
            parentMethod: React.PropTypes.func.isRequired
          };
    
           getChildContext() {
            return {
              parentMethod: (parameter_from_child) => this.parentMethod(parameter_from_child)
            };
          }
    
    parentMethod(parameter_from_child){
    // update the state with parameter_from_child
    }
    

    Now in child component (component 5 in your case) , just tell this component that it want to use context of its parent.

     static contextTypes = {
           parentMethod: React.PropTypes.func.isRequired
         };
    render(){
        return(
          this.context.parentMethod(new_state_value)}
             underlayColor='gray' >   
    
                 update state in parent component               
    
          
    )}
    

    you can find Demo project at repo

提交回复
热议问题