React passing parameter via onclick event using ES6 syntax

前端 未结 8 833
死守一世寂寞
死守一世寂寞 2020-12-04 06:34

How to pass extra parameters to an onClick event using the ES6 syntax?

For instance:

handleRemove = (e) => {

}

render() {
     
相关标签:
8条回答
  • 2020-12-04 07:07

    I am using React-Bootstrap. The onSelect trigger for dropdowns were not allowing me to pass data. Just the event. So remember you can just set any values as attributes and pick them up from the function using javascript. Picking up those attributes you set in that event target.

        let currentTarget = event.target;
        let currentId = currentTarget.getAttribute('data-id');
        let currentValue = currentTarget.getAttribute('data-value');
    
    0 讨论(0)
  • 2020-12-04 07:08

    Something nobody has mentioned so far is to make handleRemove return a function.

    You can do something like:

    handleRemove = id => event => {
      // Do stuff with id and event
    }
    
    // render...
      return <button onClick={this.handleRemove(id)} />
    

    However all of these solutions have the downside of creating a new function on each render. Better to create a new component for Button which gets passed the id and the handleRemove separately.

    0 讨论(0)
提交回复
热议问题