gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:53:29 25 4
gpt4 key购买 nike

对于 es6 中的构造函数,我们建议尽早绑定(bind)函数,例如

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。

关于javascript - 当函数在构造函数中绑定(bind)时如何在 ES6 React 中向事件处理程序添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35734008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com