3 ms·
For those who are confused... If you have a click handler "handleClick" that references "this" inside of its definition it will be broken if you do onClick = {
by poxrud 9y ago
For those who are confused...
If you have a click handler "handleClick" that references "this" inside
of its definition it will be broken if you do
onClick = {this.handleClick}
This is due to the way "this" is scoped in JS.
Dan mentions that it works fine if you instead do:
onClick = {() => this.handleClick()}
This is using the new ES6 arrow functions which fix the "this" scoping
problem.
Another alternative is to use bind() inside the onClick and set "this"
to the correct value that you want.
onClick = {this.handleClick.bind(this)}