今天在看react官網(wǎng)囊嘉,看到下面的代碼
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 為了在回調(diào)中使用 `this`格嘁,這個綁定是必不可少的
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({ isToggleOn: !state.isToggleOn }));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
官網(wǎng)有如下注釋
你必須謹(jǐn)慎對待 JSX 回調(diào)函數(shù)中的
this
笛求,在 JavaScript 中,class 的方法默認(rèn)不會綁定this
糕簿。如果你忘記綁定this.handleClick
并把它傳入了onClick
探入,當(dāng)你調(diào)用這個函數(shù)的時候this
的值為undefined
。
我記得class好像不用單獨去綁定this懂诗,于是我去看了es6蜂嗽,確實不用,但react官網(wǎng)的意思是 當(dāng)函數(shù)作為回調(diào)函數(shù)被調(diào)用時殃恒,上面代碼中onClick={this.handleClick}
其實就是把handleClick
傳入onClick作為回調(diào)函數(shù)植旧,可以理解為如下代碼
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
getAsyncData(cb) {
return cb();
}
print(){
return this.getAsyncData(this.toString)
}
}
var o=new Point(1,2)
o.print()//此時報錯 this is undefined
解決辦法有很多,其中一種就可以用bind
print(){
return this.getAsyncData(this.toString.bind(this))
}