对于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>
)
}
}
认为:
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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句