With constructors in es6, we are advised to bind functions early, e.g.
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this); // bound early
}
handleClick() {
// do stuff
}
...
}
In ES5, we could typically call something like this.handleClick.bind(this, "foo") if we wanted to preserve context AND send an extra argument. What is the best pattern for this with the new class syntax in ES6 React?
For instance, if my class looked like the code below, how would I best access the "foo" and "bar" values? (I know the answer is not bind but this is how I could best illustrate the problem).
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>
)
}
}
.bindis always thethisvalue. Therefore you would wantthis.handleClick.bind(null, "foo"). Since the function was already bound in the constructor, any value you pass as first argument is ignored.