How do I pass parent state to its child components?

前端 未结 2 1984
旧时难觅i
旧时难觅i 2021-02-01 07:27

I am new in React ES6 and I think I am modifying the state in a wrong way. My code is like this when I set state on parent component:

class App extends React.Com         


        
2条回答
  •  孤街浪徒
    2021-02-01 08:03

    If you wanna pass the state {name:"helloworld"} do it like that:

    class App extends React.Component {
    constuctor(props)  {
         super(props);
         this.state = {name:"helloworld"};
    }
     render() { 
      return( 
        
      ); 
     } 
    }
    

    and in the child component you can do:

    {this.props.name}
    

    But If you want to pass the props of the component to it's child:

       class App extends React.Component {
        constuctor(props)  {
             super(props);
             this.state = {name:"helloworld"};
        }
         render() { 
          return( 
           
          ); 
         } 
        }
    

    and in the child component you can do:

    {this.props.stuff}//place stuff by any property name in props
    

    Now if you want to update the state of parent component from the child component you will need to pass a function to the child component:

     class App extends React.Component {
        constuctor(props)  {
             super(props);
             this.state = {name:"helloworld"};
        }
        update(name){
           this.setState({name:name})// or with es6 this.setState({name})
        }
        render() { 
         return( 
          
         ); 
        } 
      }
    

    and then in child component you can use this : this.props.update('new name')

    UPDATE

    use more es6 and removed constructor

    class App extends React.Component {
        state = {name:"helloworld"};
    
        // es6 function, will be bind with adding .bind(this)
        update = name => {
           this.setState({name:name})// or with es6 this.setState({name})
        }
    
        render() { 
         // notice that we removed .bind(this) from the update
         return(
         //send multiple methods using ','
          
         ); 
        } 
      }
    

提交回复
热议问题