I know about the general theory of this
binding (function call site what matters, implicit, explicit binding, etc...) and the methods to solving the problem of this binding in React so it always points to what I want this
to be (binding in constructor, arrow functions, etc), but I am struggling to get the inner mechanisms.
Take a look at these two pieces of code:
class demo extends React.component {
goToStore(event) {
console.log(this)
}
render() {
<button onClick={(e) => this.goToStore(e)}>test</button>
}
}
vs.
class demo extends React.component {
goToStore(event) {
console.log(this)
}
render() {
<button onClick={this.goToStore}>test</button>
}
}
What I know is that:
- in both versions we end up successfully in the goToStore method, because the
this
inside therender()
method is automatically bound (by React) to the component instance - the first one succeeds because of that,
- the second one fails, because class methods in es6 are not bound to the component instance, thus resolving
this
in the method toundefined
In theory in the first version as far as I understand, the following occurs:
- the button click handler is an anonymous arrow function, so whenever I reference
this
inside of it, it picks upthis
from the environment (in this case fromrender()
) - then it calls the
goToStore
method, that is a regular function. - because the call seems to fit the rules of implicit binding (
object.function()
)object
will be the context object and in such function calls it will be used asthis
- so, inside the
goToStore
method the lexically picked up this (used as a context object) will resolve to the component instance correctly
I feel 3. and 4. is not the case here, because then it would apply to the 2. case:
<button onClick={this.goToStore}>test</button>
Also with this
the context object.
What is happening exactly in this particular case, step-by-step?
See Question&Answers more detail:os