使用 ES6 语法通过 onclick 事件响应传递参数 [英] React passing parameter via onclick event using ES6 syntax
问题描述
如何使用 ES6 语法将额外参数传递给 onClick 事件?
How to pass extra parameters to an onClick event using the ES6 syntax?
例如:
handleRemove = (e) => {
}
render() {
<button onClick={this.handleRemove}></button>
}
我想像这样将一个 id 传递给 handleRemove
函数:
I want to pass an id to the handleRemove
function like this:
<button onClick={this.handleRemove(id)}></button>
推荐答案
请记住,在 onClick={ ... }
中,...
是一个 JavaScript 表达式.所以
Remember that in onClick={ ... }
, the ...
is a JavaScript expression. So
... onClick={this.handleRemove(id)}
与
var val = this.handleRemove(id);
... onClick={val}
换句话说,您立即调用 this.handleRemove(id)
,并将该值传递给 onClick
,这不是您想要的.
In other words, you call this.handleRemove(id)
immediately, and pass that value to onClick
, which isn't what you want.
相反,您想创建一个 new 函数,其中一个参数已经预填充;基本上,您需要以下内容:
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}
在 ES5 JavaScript 中有一种表达方式:Function.prototype.bind
.
There is a way to express this in ES5 JavaScript: Function.prototype.bind
.
... onClick={this.handleRemove.bind(this, id)}
如果你使用 React.createClass
,React 会在实例方法上自动为你绑定 this
,除非你把它改成 this.handleRemove,否则它可能会报错.绑定(空,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)}
这篇关于使用 ES6 语法通过 onclick 事件响应传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!