How to access one component's state from another component

前端 未结 5 640
遥遥无期
遥遥无期 2020-12-09 07:51

How do I access one component\'s state in another component? Below is my code and I\'m trying to access the state of component a in component b.

5条回答
  •  萌比男神i
    2020-12-09 08:18

    in the child component create function that sets the state:

    changeTheState(){
       this.setState({something:"some value"})
    }
    

    and in parent component give the child a ref as following:

     this._child = component}/>
    

    then in parent make a function to access the changeTheState()

      parentFunction(){
    this._child.changeTheState();
    

    } and just use the parentFunction.

提交回复
热议问题