How to update parent's state in React?

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

    I've used a top rated answer from this page many times, but while learning React, i've found a better way to do that, without binding and without inline function inside props.

    Just look here:

    class Parent extends React.Component {
    
      constructor() {
        super();
        this.state={
          someVar: value
        }
      }
    
      handleChange=(someValue)=>{
        this.setState({someVar: someValue})
      }
    
      render() {
        return 
      }
    
    }
    
    export const Child = ({handler}) => {
      return 

    The key is in an arrow function:

    handleChange=(someValue)=>{
      this.setState({someVar: someValue})
    }
    

    You can read more here. Hope this will be useful for somebody =)

提交回复
热议问题