使用ES6语法通过onclick事件反应传递参数

reactjs React.js

小胖蛋蛋

2020-03-12

如何使用ES6语法将额外的参数传递给onClick事件?

例如:

handleRemove = (e) => {

}

render() {
     <button onClick={this.handleRemove}></button>
}

我想将id传递给这样的handleRemove函数:

<button onClick={this.handleRemove(id)}></button>

第1212篇《使用ES6语法通过onclick事件反应传递参数》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
逆天L 2020.03.12

使用button元素value属性传递id,如下

<button onClick={this.handleRemove} value={id}>Remove</button>

然后在handleRemove中,从event中读取值为:

handleRemove(event) {
...
 remove(event.target.value);
...
}

这样,您避免了每次重新渲染此组件时都创建一个新函数(与使用箭头函数相比)。

nick 2020.03.12

到目前为止,没有人提到的是使handleRemove返回函数。

您可以执行以下操作:

handleRemove = id => event => {
  // Do stuff with id and event
}

// render...
  return <button onClick={this.handleRemove(id)} />

但是,所有这些解决方案都有在每个渲染器上创建新功能的缺点。最好为Button创建一个新组件,idhandleRemove分别传递

Green樱 2020.03.12
onClick={this.handleRemove.bind(this, id)}
米亚凯 2020.03.12

使用箭头功能,如下所示:

<button onClick={()=>{this.handleRemove(id)}}></button>
猿EvaL 2020.03.12

I use the following code:

<Button onClick={this.onSubmit} id={item.key} value={shop.ethereum}>
    Approve
</Button>

Then inside the method:

onSubmit = async event => {
    event.preventDefault();
    event.persist();
    console.log("Param passed => Eth addrs: ", event.target.value)
    console.log("Param passed => id: ", event.target.id)
    ...
}

As a result:

Param passed in event => Eth addrs: 0x4D86c35fdC080Ce449E89C6BC058E6cc4a4D49A6

Param passed in event => id: Mlz4OTBSwcgPLBzVZ7BQbwVjGip1

小宇宙西里 2020.03.12

请记住,中onClick={ ... }...是JavaScript表达式。所以

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

是相同的

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

换句话说,您this.handleRemove(id)立即调用,并将该值传递给onClick,这不是您想要的。

相反,您想创建一个函数,其中一个参数已经预先填充;本质上,您需要以下内容:

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

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

如果使用React.createClass,React会自动this为您绑定实例方法,除非将其更改为,否则它可能会抱怨this.handleRemove.bind(null, id)

您也可以简单地内联定义函数;如果您的环境或编译器支持,则可以使用箭头功能将其缩短

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

如果您需要访问该事件,则可以将其传递:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android