简体   繁体   中英

Passing method to child Component

My React app has several similar custom buttons that perform different tasks. The UI is similar among all the buttons, what changes is the action each one must trigger and the title.

The working code for the parent Component containing the buttons is (similar) to the following:

class Page extends Component { 
    constructor(props) {
        super(props);
    }

    action1(){
       //... do stuff...
    }

    action2(){
       //... do stuff...
    }

    render(){

        return(
            <div className="table-row">

                <div className="table-cell">
                    <div className="button" 
                        onClick={this.action1.bind(this)}>{"button1"}
                    </div>
                </div>

                <div className="table-cell">
                     <div className="button" 
                          onClick={this.action2.bind(this)}>{"button2"}
                     </div>
                </div> 
            </div>
        );
    }
}

Is it possible to pass a method to the child component the same way it is done for a variable value? I want to turn it into something like this:

class Page extends Component { 
    constructor(props) {
        super(props);
    }

    action1(){
       //... do stuff...
    }

    action2(){
       //... do stuff...
    }

    render(){

        return(
            <div className="table-row">

                <div className="table-cell">
                    <CustomButton action={this.action1.bind(this)} title={"button1"}/>
                </div>

                <div className="table-cell">
                     <CustomButton action={this.action2.bind(this)} title={"button2"}/>
                </div> 
            </div>
        );
    }
}

class CustomButton extends Component{
    constructor(props){
        super(props);
    }

    render() {
        return (
            <div className="table-cell"><div className="button" 
                onClick= {this.props.action}>{this.props.title}
            </div>
        );
    }
}

What would be the correct way to handle this situation and the theory behind it?

I'm using React with Meteor, in case it makes a difference.

You can pass props to components. Passed props can have any data type of javascript.

In your case, you want to pass an action props which has a function as the value. Then you access action props in your component and use it.

In short, there is no theory behind it. What you are doing is correct. This is how react handles passing data to other components. Note that this is not the only way to pass data to child components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM