如何在ES6类中使用参数调用函数

How to call a function with arguments in an ES6 class?

本文关键字:参数 调用 函数 ES6      更新时间:2023-09-26

我正在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>
}