New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
With React ES6 syntax class methods are not bind to the instance context #4065
Comments
React's ES6 classes have no autobinding. This is documented here: https://facebook.github.io/react/docs/reusable-components.html#no-autobinding The reason is that javascript's ES6 classes have no autobinding neither. React tries to not reinvent stuff that is already in javascript. ES5 has no nice syntax for classes, so React had to invent it's own classes. But now with ES6 classes we can just use standard javascript. |
Yeah, so this is sort of confusing
And here was my problem http://stackoverflow.com/questions/30726162/how-to-properly-bind-current-object-context-in-es6-using-babelify And it turns out that arrow functions is invalid syntax in ES6 classes |
That means that you can do either <input type="text" onChange={this.handleChange.bind(this)} /> or <input type="text" onChange={(e) => this.handleChange(e)} /> or <input type="text" onChange={(e) => this.setState({ demo: e.target.value })} /> |
Still kind of ugly, huh? Ok man, thanks, I think it's better then binding contexts in constructor |
You could also use es7 bind prefix operator
@vladmiller If that works for you please close this issue. |
This was called out in all of our documentation about ES6 classes and there are a number of issue on it. Closing this out but feel free to follow along in one of the other places. |
Different ways of binding
} <input type="text" onChange={(e) => this.handleChange(e)} /> <input type="text" onChange={(e) => this.handleChange.bind(this)(e)} /> or <input type="text" onChange={(e) => this.handleChange.bind(this,e)()} /> or use arrow functions for handlers handleChange = (e) => { |
Here is the example
http://jsbin.com/citafaradu/2/edit?js,console,output
The text was updated successfully, but these errors were encountered: