简体   繁体   中英

Props not getting passed to onClick function

I have a onClick that uploads data, I need to pass props to that onclick function from the render its in.

onClick={this.handleEditsUpload}

to

handleEditsUpload() {
  const { selected } = this.props;
}

selected is showing as selected: [] in handleEditsUpload() .

I have tried passing the props by doing:

onClick={this.handleEditsUpload(...this.props)}

which I thought would work as I am doing this elsewhere.

Not sure where to go from here, any suggestions please?

You no need to specifically pass props to handleEditsUpload event handler function

Change

  onClick={this.handleEditsUpload(...this.props)}

To

 onClick={this.handleEditsUpload}

Because this.props are available directly inside handleEditsUpload.

What you need to make sure is that whether you did binding for handleEditsUpload in constructor. if not then add below line in constructor

      this.handleEditsUpload = this.handleEditsUpload.bind(this);

So now you will have access to props inside handleEditsUpload function

    handleEditsUpload(){
         const { selected } = this.props;
    }

There is no need for passing props to handler function hence I don't recommend doing that. If you still want to do in that approach then call the function in arrow way because you need to pass params

   onClick={() => this.handleEditsUpload(...this.props)}

You are sending onClick a function's result instead of its reference. What happen during onClick={this.handleEditsUpload(...this.props)} is that handleEditsUpdload is called with the provided props, then its return value (null in this case) is assigned to onClick.

If you want to call handleEditsUpload when the button is clicked, give it a function reference instead:

onClick={() => this.handleEditsUpload(...this.props)}

The difference is that this time you're assigning the arrow function () => this.handleEditsUpload(...this.props) to onClick, instead of a return value.

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