Binding, ES6 classes, and onChange
See original GitHub issueWhen using ES6 classes, autobinding doesn’t happen, as we all hopefully know by now 😃.
So when I do:
<button onClick={this.handleClick}>Test Button</button>
I’d expect that “this” inside of my handleClick
function in my class is undefined. This is, in fact, what happens.
However, when I do:
<input onChange={this.handleChange} type="checkbox" />
…“this” inside of my handleChange
function is the input component’s constructor.
Obviously, if I just bind my functions all the time, the problem is resolved. But since “this.setState” exists on the constructor…I was calling this.setState inside my handleChange function, not getting an error, and nothing was happening. So it was confusing to track down.
Admittedly I’m not immediately sure what to do about this…but I thought I’d make an issue and open it up for discussion.
Issue Analytics
- State:
- Created 8 years ago
- Comments:17 (4 by maintainers)
@Zenwolf you still need to
.bind(this)
or you can use the experimental ES7 function’s binding operator::
Alternatively, you may use the
@autobind
Decorator pattern from ES7 Stage 1 on the function using theautobind-decorator
. Unlike function binding approach suggested by @MyBoon use of the decorator does not require use of the experimental Strawman (Stage 0) proposal.The downside to using
autobind-decorator
is that it’s function-level only, so you may end up using it several times to decorate class methods as more of them require use of the class’this
context.It seems to me the most favorable approach would be to use the class-level
@autobind
found incore-decorators
if anything.