当事件处理程序使用this
时(像下面的handleClick
一样使用this.setState
),你必须将事件处理程序与this
关键词。否则,您需要使用 the arrow function .
例如
//This function isn't bound whilst using "this" keyword inside of it.
//Still, it works because it uses an arrow function
handleClick = () => {
this.setState({
isClicked:true
});
}
render() {
return (
<div className="App">
<button onClick={this.handleClick}>Click</button>
</div>
);
}
但是,使用上述方法,您不能传递参数。您需要使用...
bind(this, param)
在函数之后- 匿名箭头函数
即
<button onClick={this.handleClick}>Click</button>
will be
<button onClick={this.handleClick.bind(this, 111)}>Click</button>
or
<button onClick={() => this.handleClick(111)}>Click</button>
这是问题。
将参数传递给事件处理程序的最有效方法是什么?
根据 the official doc ,使用 bind()
会破坏性能,因为...
Using Function.prototype.bind in render creates a new function each time the component renders
使用匿名箭头函数也是如此。医生说...
Using an arrow function in render creates a new function each time the component renders
那么,传递参数的最有效方式是什么?
我们将不胜感激。
附言
有人问param
是怎么确定的。这将动态确定(即不总是 111
)。因此,它可以来自状态、 Prop 或此类中定义的其他一些函数。
最佳答案
不是在 .bind
中创建匿名箭头函数,而是在 render()
中创建绑定(bind)/匿名函数 render()
,例如在实例化对象、构造函数或类似的东西上,并使用对该单一(永远不会重新创建)函数的引用。例如,运行一次:
this.boundHandleClick = this.handleClick.bind(this, 111);
或
this.boundHandleClick = () => this.handleClick(111);
然后,在render
中,引用boundHandleClick
:
return (
<div className="App">
<button onClick={this.boundHandleClick}>Click</button>
</div>
);
如果您需要使用 render
的参数 (111
) inside,那么您可以使用对象查找来查看是否有绑定(bind)函数该参数还存在。如果是,只需使用该绑定(bind)函数 - 否则,创建它(一次,这样您以后使用该参数时就不必再次创建):
this.boundClicks = {};
// ...
if (!this.boundClicks['111']) this.boundClicks['111'] = () => this.handleClick(111);
return (
<div className="App">
<button onClick={this.boundClicks['111']}>Click</button>
</div>
);
关于javascript - react .js : the most efficient way to pass a parameter to an event handler without bind() in a component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52788613/