当函数绑定在构造函数中时,如何在 ES6 React 中向事件处理程序添加参数

How to add arguments to event handler in ES6 React when functions are bound in constructor

本文关键字:事件处理 React 程序 参数 添加 ES6 绑定 函数 构造函数      更新时间:2023-09-26

对于 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>
    )
  }
}