[英]How to call a function with arguments in an ES6 class?
I am making an app in Reactjs using an ES6 class for a component. 我正在使用ES6类的组件在Reactjs中制作一个应用程序。 The code works as intended until I want to call a function inside the class with arguments. 该代码按预期工作,直到我想在类中使用参数调用函数为止。
SampleClass.js SampleClass.js
class SampleClass extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
backgroundColor: 'yellow'
}
}
onChangeBackgroundColor(backgroundColor) {
this.setState({
backgroundColor: backgroundColor
})
}
render() {
return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}>
<span onClick={this.onChangeBackgroundColor.bind(this)} style={{background: 'white'}}>
Change element style
</span>
</div>
}
}
React.render(<SampleClass />, document.getElementById('container'));
I am able to call a function fine without arguments like this.onChangeBackgroundColor.bind(this)
. 我可以很好地调用一个没有this.onChangeBackgroundColor.bind(this)
这样的参数的函数。
However, when I try passing an argument to the function, I get an error in the console Uncaught TypeError: Cannot read property 'bind' of undefined
. 但是,当我尝试将参数传递给函数时,在控制台中出现错误Uncaught TypeError: Cannot read property 'bind' of undefined
。
Ref fiddle: https://jsfiddle.net/purezen/s6ap3m8s/3/ 参考小提琴: https : //jsfiddle.net/purezen/s6ap3m8s/3/
this.onChangeBackgroundColor.bind(this, arg1, arg2)
Your arguments should go in the bind call, after this
, if you want them to be bound to the function. 如果希望将参数绑定到函数,则应在this
之后将其放在bind调用中。
As @ivarni stated and per the React docs it is best to bind in the constructor, see the below link for more information 如@ivarni所述,根据React文档,最好绑定到构造函数中,有关更多信息,请参见以下链接。
"We recommend that you bind your event handlers in the constructor so they are only bound once for every instance:" “我们建议您将事件处理程序绑定到构造函数中,这样对于每个实例它们都只绑定一次:”
https://facebook.github.io/react/docs/reusable-components.html https://facebook.github.io/react/docs/reusable-components.html
A better way to deal with click binding to correct value of this with passed parameters is using ES6 lambdas () =>
as they lexically bind the correct value of this: 处理单击绑定以使用传递的参数正确设置此值的一种更好方法是使用ES6 lambdas () =>
因为它们按词法绑定此正确的值:
render () {
return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}>
<span onClick={() => this.onChangeBackgroundColor(arg1, arg2)} style={{background: 'white'}}>
Change element style
</span>
</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.