React passing parameter via onclick event using ES6 syntax

前端 未结 8 890
死守一世寂寞
死守一世寂寞 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 06:45

    Remember that in onClick={ ... }, the ... is a JavaScript expression. So

    ... onClick={this.handleRemove(id)}
    

    is the same as

    var val = this.handleRemove(id);
    ... onClick={val}
    

    In other words, you call this.handleRemove(id) immediately, and pass that value to onClick, which isn't what you want.

    Instead, you want to create a new function with one of the arguments already prefilled; essentially, you want the following:

    var newFn = function() {
      var args = Array.prototype.slice.call(arguments);
    
      // args[0] contains the event object
      this.handleRemove.apply(this, [id].concat(args));
    }
    ... onClick={newFn}
    

    There is a way to express this in ES5 JavaScript: Function.prototype.bind.

    ... onClick={this.handleRemove.bind(this, id)}
    

    If you use React.createClass, React automatically binds this for you on instance methods, and it may complain unless you change it to this.handleRemove.bind(null, id).

    You can also simply define the function inline; this is made shorter with arrow functions if your environment or transpiler supports them:

    ... onClick={() => this.handleRemove(id)}
    

    If you need access to the event, you can just pass it along:

    ... onClick={(evt) => this.handleRemove(id, evt)}
    

提交回复
热议问题