How to update parent's state in React?

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

    so, if you want to update parent component,

     class ParentComponent extends React.Component {
            constructor(props){
                super(props);
                this.state = {
                   page:0
                }
            }
    
            handler(val){
                console.log(val) // 1
            }
    
            render(){
              return (
                  <ChildComponent onChange={this.handler} />
               )
           }
       }
    
    
    class ChildComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                 page:1
            };
        }
    
        someMethod = (page) => {
            this.setState({ page: page });
            this.props.onChange(page)
        }
    
        render() {
            return (
           <Button
                onClick={() => this.someMethod()} 
           > Click
            </Button>
          )
       }
    }
    

    Here onChange is an attribute with "handler" method bound to it's instance. we passed the method handler to the Child class component, to receive via onChange property in its props argument.

    The attribute onChange will be set in a props object like this:

    props ={
    onChange : this.handler
    }
    

    and passed to the child component

    So the Child component can access the value of name in the props object like this props.onChange

    Its done through the use of render props.

    Now the Child component has a button “Click” with an onclick event set to call the handler method passed to it via onChnge in its props argument object. So now this.props.onChange in Child holds the output method in the Parent class Reference and credits: Bits and Pieces

    0 讨论(0)
  • 2020-11-22 09:47

    Most of the answers given above are for React.Component based designs. If your are using useState in the recent upgrades of React library, then follow this answer

    0 讨论(0)
提交回复
热议问题