How to update parent's state in React?

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

    I found the following working solution to pass onClick function argument from child to the parent component with param:

    parent class :

    class Parent extends React.Component {
    constructor(props) {
        super(props)
    
        // Bind the this context to the handler function
        this.handler = this.handler.bind(this);
    
        // Set some state
        this.state = {
            messageShown: false
        };
    }
    
    // This method will be sent to the child component
    handler(param1) {
    console.log(param1);
        this.setState({
            messageShown: true
        });
    }
    
    // Render the child component and set the action property with the handler as value
    render() {
        return 
    }}
    

    child class :

    class Child extends React.Component {
    render() {
        return (
            
    {/* The button will execute the handler function set by the parent component */}
    ) } }

提交回复
热议问题