作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
对于 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/
我是一名优秀的程序员,十分优秀!