How to update parent's state in React?

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

    It seems that we can only pass data from parent to child as react promotes Unidirectional Data Flow, but to make parent update itself when something happens in its "child component", we generally use what is called a "callback function".

    We pass the function defined in the parent to the child as "props" and call that function from the child triggering it in the parent component.


    class Parent extends React.Component {
      handler = (Value_Passed_From_SubChild) => {
        console.log("Parent got triggered when a grandchild button was clicked");
        console.log("Parent->Child->SubChild");
        console.log(Value_Passed_From_SubChild);
      }
      render() {
        return 
      }
    }
    class Child extends React.Component {
      render() {
        return 
      }
    }
    class SubChild extends React.Component { 
      constructor(props){
       super(props);
       this.state = {
          somethingImp : [1,2,3,4]
       }
      }
      render() {
         return 

    In this example we can make data pass from SubChild -> Child -> Parent by passing function to its direct Child.

提交回复
热议问题