当函数绑定在构造函数中时,如何在 ES6 React 中向事件处理程序添加参数
How to add arguments to event handler in ES6 React when functions are bound in constructor
对于 es6 中的构造函数,建议尽早绑定函数,例如
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this); // bound early
}
handleClick() {
// do stuff
}
...
}
在 ES5 中,如果我们想保留上下文并发送一个额外的参数,我们通常可以调用类似 this.handleClick.bind(this, "foo")
的东西。ES6 React 中新类语法的最佳模式是什么?
例如,如果我的类看起来像下面的代码,我将如何最好地访问 "foo"
和 "bar
" 值?(我知道答案不是bind
但这是我最好地说明问题的方式)。
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this); // bound early
}
handleClick(event, value) {
// do stuff with value ("foo" or "baz")
}
render() {
return (
<div>
<button onClick={this.handleClick.bind("foo")} /> // incorrect code
<button onClick={this.handleClick.bind("bar")} /> // incorrect code
</div>
)
}
}
认为:
onClick={this.handleClick.bind(this)}
与以下相同:
onClick={e => this.handleClick(e)}
所以你可以做到:
<button onClick={e => this.handleClick(e, 'foo')} />
<button onClick={e => this.handleClick(e, 'baz')} />
最后,这一切都只是JavaScript。
在 ES5 中,如果我们想保留上下文并发送额外的参数,我们通常可以调用类似
this.handleClick.bind(this, "foo")
的东西。
你也可以在 ES6 中做完全相同的事情。这不像bind
从语言中删除了:-)
class App extends React.Component {
constructor(props) {
super(props);
this.handleFooClick = this.handleClick.bind(this, "foo"); // bind early
}
handleClick(value, event) {
// ^^^^^^ notice the bound values come first
…
}
render() {
return (
<div>
<button onClick={this.handleFooClick} /> // use early-bound
<button onClick={this.handleClick.bind(this, "bar")} /> // bind late
<button onClick={event => this.handleClick("foobar", event)} /> // arrow function
</div>
)
}
}
相关文章:
- keyup事件处理程序更改焦点不适用于快速键入
- 为什么removeEventListener不适用于React安装的事件处理程序
- React.js-通过事件处理程序更改所有者组件的状态
- 为什么当同级节点的“display”属性发生更改时,React 组件的 onClick 事件处理程序不会触发
- 当函数绑定在构造函数中时,如何在 ES6 React 中向事件处理程序添加参数
- 如何在React中传递事件处理程序函数
- React-如何与事件处理程序一起使用bind并保留事件对象
- React.js onShow事件处理程序
- 如何在react组件中编写内联js事件处理程序代码;这个“;
- React事件处理程序未被删除
- 在React中,如何在匿名函数中放置事件处理程序来解决绑定问题?
- 处理React中的onClick事件
- 处理React JS中的关键事件
- 如何将事件处理程序传递给React中的子组件
- 用于滚动的React被动事件处理程序
- 在React的内部标记中添加事件处理程序/道具
- 为服务器端呈现的React模板绑定事件处理程序
- onClick按钮事件处理程序在使用react.js的JSX页面时不起作用
- 在REACT,js中钩子事件处理程序时出现UnCaughtType错误
- react.js:如何将传入的事件处理程序绑定到子组件