You need set this
to methods in case, for example, if you need pass function reference to event handlers, however you don't need set this
for every method.,
class Counter extends React.Component {
constructor() {
super();
this.tick = this.tick.bind(this);
}
tick() {
// this refers to Counter
}
fn() {
// this refers to Counter
}
withoutBind() {
// this will be undefined or window it depends if you use "strict mode" or not
}
render() {
this.fn(); // this inside this method refers to Counter
// but if you will do like this
const fn = this.fn;
fn(); // this will refer to global scope
return <div>
<button onClick={this.tick}>1</button>
<button onClick={this.withoutBind}>2</button>
</div>;
}
}
Example
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…