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

Kev*_* K. 9 javascript ecmascript-6 reactjs

使用es6中的构造函数,我们建议尽早绑定函数,例如

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this); // bound early
  }

  handleClick() {
    // do stuff
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

在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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

elc*_*nrs 16

认为:

onClick={this.handleClick.bind(this)}
Run Code Online (Sandbox Code Playgroud)

是相同的:

onClick={e => this.handleClick(e)}
Run Code Online (Sandbox Code Playgroud)

所以你可以这样做:

    <button onClick={e => this.handleClick(e, 'foo')} />
    <button onClick={e => this.handleClick(e, 'baz')} />
Run Code Online (Sandbox Code Playgroud)

最后,它只是JavaScript.


Ber*_*rgi 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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)