javascript - react .js : the most efficient way to pass a parameter to an event handler without bind() in a component

标签 javascript reactjs

当事件处理程序使用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>
    );
}

但是,使用上述方法,您不能传递参数。您需要使用...

  1. bind(this, param) 在函数之后
  2. 匿名箭头函数

<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/

相关文章:

javascript - 错误: SyntaxError: Unexpected token { in JSON at position 4

javascript - 在我的案例中如何禁用表单提交

javascript - JavaScript 的对象字面量和在控制台登录时显示为已命名的对象之间有什么区别?

javascript - 类型 'length' 上不存在属性 '{ [key: number]: any[]; }' 。在 React/Angular 中的状态变量中

javascript - React - 使用多个数组进行映射

javascript - 如何将状态重置为初始状态?

reactjs - 如何使用 FormattedMessage 翻译 MaterialTable ReactJS 的 searchPlaceholder

reactjs - 将表单与 MUI onSubmit 方法一起使用不起作用

javascript - 是否可以删除状态栏或禁用 showModalDialog 上的关闭按钮?

javascript - 使用 JQuery 或 Javascript 获取设备 ID