简体   繁体   中英

Passing a parameter to an event handler in the parent class from a child class ReactJS

I am trying to pass a parameter to an event handler in a parent class, but am having some difficulty. I have done a good amount of research and am close to answer, but something's not quite working. Below I will give a basic hypothetical example of what I would like to do that doesn't work.

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

       handleClick(i){
           return event => console.log(i);
       }

       render(){
          return <Child onClick={this.handleClick}></button>;
       }
}

class Child extends React.Component {
       render() {
            const myVar = 2;
            return <button onClick={this.props.onClick(myVar)}></button>;
       }
}

I know the onClick prop that is passed to the Child is not a function, so I am unable to pass parameters directly to it. What is the best way to go about doing this? Thanks for you help!

Make the following update to your code

class Child extends React.Component{
       render(){
            const var = 2;
            return <button onClick={ () => {this.props.onClick(var)} }</button>;
       }
}

Furthermore, you should refactor the following method used by parent as so. You are passing e needlessly.

handleClick(i){
    console.log(i);
}

The onClick on your child component was immediately invoked instead of waiting for the onClick event to fire.

You can't do

handleClick(i){
           return (e => {console.log(i)});
       }

instead, try

handleClick(i){
          console.log(i)
       }

and move the event handling to where it is being called. So instead of

<button onClick={this.props.onClick(var)}</button>

You want to try

<button onClick={e => this.props.onClick(var)}</button>

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