How to invoke a function in parent component from

2020-05-08 07:13发布

问题:

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.clicked = this.clicked.bind(this);
    }

    getChildrenValues(){
        console.log("Children values");
    }

    render(){
        return <div>
            Parent 

            <Component1>

                <Component2>
                    <Child />   

                </Component2>

            </Component1>

        </div>
    }
}


class Child extends React.Component{
    constructor(props){
        super(props);
        this.clicked = this.clicked.bind(this);
    }

    clicked(){
        this.props.dispatch({type: "InvokeParent"});
    }

    render(){
        return <div>
            <button onClick = {this.clicked}>Click Here</button>
        </div>
    }
}

how to invoke getChildrenValues function from "Child" component. I am trying to get all children values from parent component and submit but I do not know how to trigger that function in redux. In flux I used to do addChangeListener and trigger that function.

回答1:

Just based on your example, I would say this situation won't involve redux at all. Redux is a tool for managing global state. Nothing in this example is touching state.

For this example code to work pass your method down as a prop and invoke it on click. This can be messy if depending on how nested the child component is.

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.clicked = this.clicked.bind(this);
    }

    getChildrenValues(){
        console.log("Children values");
    }

    render(){
        return <div>
            Parent 

            <Component1>

                <Component2>
                    <Child invokeParent={this.getChildrenValues} />   

                </Component2>

            </Component1>

        </div>
    }
}


class Child extends React.Component{
    constructor(props){
        super(props);
        this.clicked = this.clicked.bind(this);
    }

    clicked(){
        this.props.dispatch({type: "InvokeParent"});
    }

    render(){
        return <div>
            <button onClick = {this.props.invokeParent}>Click Here</button>
        </div>
    }
}