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

时间:2016-03-01 21:35:43

标签: javascript reactjs ecmascript-6

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

2 个答案:

答案 0 :(得分:16)

想一想:

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。

答案 1 :(得分:6)

  

在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>
    )
  }
}