如何在ES6类中使用参数调用函数
How to call a function with arguments in an ES6 class?
我正在Reactjs中使用ES6类为组件制作一个应用程序。代码按预期工作,直到我想用参数调用类内的函数为止。
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'));
我能够在没有像this.onChangeBackgroundColor.bind(this)
这样的参数的情况下调用函数fine。
但是,当我尝试将参数传递给函数时,控制台中出现错误CCD_ 2。
参考小提琴:https://jsfiddle.net/purezen/s6ap3m8s/3/
this.onChangeBackgroundColor.bind(this, arg1, arg2)
如果您希望参数绑定到函数,那么它们应该在this
之后的绑定调用中。
正如@ivarni所说,根据React文档,最好在构造函数中绑定,有关更多信息,请参阅下面的链接
"我们建议您在构造函数中绑定事件处理程序,以便每个实例只绑定一次:"
https://facebook.github.io/react/docs/reusable-components.html
我编辑了你的fiddle,传递了red
值,它就工作了。
你可以在这里看到
您需要将参数传递给bind
函数
处理点击绑定以通过传递的参数更正该值的更好方法是使用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>
}
相关文章:
- 使用html表单中的参数调用JavaScript函数
- 如何在ES6类中使用参数调用函数
- 如何使用OnClick事件通过参数调用来调用PHP函数
- Worklight Client使用自定义BODY参数调用过程
- 如何在jQuery AJAX中使用参数调用PHP函数
- 如何使用参数调用java脚本函数,其中参数来自字符串变量
- 使用数组-apply()中的参数调用函数,但不使用上下文参数
- 如何使用JQuery.ech()中分配给变量的参数调用函数
- 如何用参数调用coffescript函数
- 使用与父函数相同的参数调用函数
- 使用动态参数调用函数
- 使用来自 asp.net 的参数调用 Java 脚本函数
- 设置 JavaScript 以使用不同的参数调用函数
- 在 javascript 函数中使用参数调用 java 函数
- 使用参数调用 JavaScript 处理程序
- 如何使用在 jscript 中声明的参数调用 Html.RenderAction()
- Firebase 承诺 - Query.once 失败:使用 1 个参数调用.预计至少 2
- 有没有办法通过另一个函数参数调用函数
- 在 PHP 中使用多个参数调用 js 函数
- 使用来自另一个函数的对象参数调用函数