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

Javascript 当函数在构造函数中绑定时,如何向ES6中的事件处理程序添加参数,javascript,reactjs,ecmascript-6,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中,如果我们想保留上下文并发送额外参数,通常可以

对于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中新的类语法的最佳模式是什么

例如,如果我的类看起来像下面的代码,我如何才能最好地访问
“foo”
“bar
”值?(我知道答案不是
bind
,但这是我能最好地说明问题的方式)

类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
this.handleClick=this.handleClick.bind(this);//提前绑定
}
handleClick(事件、值){
//做有价值的事情(“foo”或“baz”)
}
render(){
返回(
//错误代码
//错误代码
)
}
}
想想:

onClick={this.handleClick.bind(this)}
同:

onClick={e => this.handleClick(e)}
因此,您可以:

    <button onClick={e => this.handleClick(e, 'foo')} />
    <button onClick={e => this.handleClick(e, 'baz')} />
this.handleClick(e'foo')}>
this.handleClick(e,'baz')}/>
最后,这一切都只是JavaScript

在ES5中,如果我们想保留上下文并发送额外参数,通常可以调用类似
this.handleClick.bind(this,“foo”)
的函数

您也可以在ES6中执行完全相同的操作。这不像是从语言中删除了
bind
:)

类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
this.handleFooClick=this.handleClick.bind(this,“foo”);//提前绑定
}
handleClick(值、事件){
//^^^^^^^请注意,绑定值排在第一位
…
}
render(){
返回(
//使用早绑定
//迟到
this.handleClick(“foobar”,event)}///arrow函数
)
}
}

@elclanrs:Oops,在
bind
调用中弄乱了参数顺序是一个输入错误
this.handleClick.bind(this,“bar”)
应该相当于
(…args)=>this.handleClick(“bar”,“args”)
这个答案将我的培根保存在一个普通的ES6/babel with Class场景中,谢谢。请注意,每次呈现组件时,它都会包装一个新函数,稍微放慢应用程序的速度。@JF然后使用我已经展示过的早期绑定选项
的第一个参数。bind
始终是
这个
值。因此,您需要
this.handleClick.bind(null,“foo”)
。由于函数已在构造函数中绑定,因此将忽略作为第一个参数传递的任何值。此答案中“错误代码”的确切含义是什么?这种方式将在每个呈现中创建一个新函数,这会减慢应用程序的速度,因为React必须注销旧处理程序并注册新处理程序。
    <button onClick={e => this.handleClick(e, 'foo')} />
    <button onClick={e => this.handleClick(e, 'baz')} />
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>
    )
  }
}