Sometimes I forgot the rules, and I hope to make a general rule here, and can other user provide some insight as to whether this is a correct summary?
In ReactJS, I think one common pitfall is, when we see
Form 1
class Toggle extends React.Component {
handleClick() {
console.log(this);
}
render() {
return (
<button onClick={this.handleClick}>
Click Me
</button>
);
}
}
I think when I see it as this.handleClick
, I might have an initial impression that, it looks like it is the form of this.handleClick()
, so when handleClick
is invoked, then the this
should be bound to the correct object. However, using this form, is actually the same as
render() {
let fn = this.handleClick;
return (
<button onClick={fn}>
Click Me
</button>
);
}
So in fact, it is a mistake. this.handleClick
is not invoked as this.handleClick()
, but the value of this.handleClick
is first evaluated, then then provided to onClick
, which probably is using the form addEventListener('click', fn)
.
If we need this form, we need to use something like
let fn = this.handleClick.bind(this);
or alternatively, it is directly putting it there
<button onClick={this.handleClick.bind(this)}>
Form 2
class Toggle extends React.Component {
handleClick() {
console.log(this);
}
render() {
return (
<button onClick={() => this.handleClick()}>
Click Me
</button>
);
}
}
So in this case, it is similar to using fn
:
let fn = () => this.handleClick();
and fn
, when invoked, has the this
bound to the correct object, because it is really invoked by the form this.handleClick()
. But this form has the criticism of an anonymous function always being created.
Form 3
class Toggle extends React.Component {
handleClick = () => {
console.log(this);
}
render() {
return (
<button onClick={this.handleClick}>
Click Me
</button>
);
}
}
So in this case, this.handleClick
is an arrow function, and the this
is the lexical this
, and therefore refers to the correct object.
And I think Form 1 and Form 3 are the preferred methods. Is there any misconception for these three forms? Anything else we should take note of, in terms of master these 3 forms?
question from:
https://stackoverflow.com/questions/65920290/is-it-true-that-there-are-three-ways-to-make-sure-this-is-correctly-bound-in-t