简体   繁体   中英

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. The code works as intended until I want to call a function inside the class with arguments.

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) .

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 .

Ref fiddle: 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.

As @ivarni stated and per the React docs it is best to bind in the constructor, see the below link for more information

"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

I edited your fiddle, passing red value, and it works.

You can see it here

You need to pass the arguments to the bind function

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:

render () {
  return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}>
    <span onClick={() => this.onChangeBackgroundColor(arg1, arg2)} style={{background: 'white'}}>
        Change element style
    </span>
  </div>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM