下面是一段react寫(xiě)的簡(jiǎn)單動(dòng)態(tài)效果,但有分地方不清楚。在定時(shí)器裡的結(jié)尾為什麼要加bind(this),它的作用是什麼,我缺了那一塊的知識(shí)點(diǎn)導(dǎo)致我不清楚要加bind(this)的?
var Hello = React.createClass({
getInitialState: function () {
return {
opacity: 1.0
};
},
componentDidMount: function () {
this.timer = setInterval(function () {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
}
this.setState({
opacity: opacity
});
}.bind(this), 100);
},
render: function () {
return (
<p style={{opacity: this.state.opacity}}>
Hello {this.props.name}
</p>
);
}
});
ReactDOM.render(
<Hello name="world"/>,
document.body
);
認(rèn)證高級(jí)PHP講師
兩個(gè)知識(shí)點(diǎn):
bind()
this 指向
具體到這個(gè)例子,如果不使用bind()
而直接呼叫 setInterval 中定義的匿名函數(shù),函數(shù)內(nèi)部的 this 是指向 window 物件的。匿名函數(shù)內(nèi)部顯然需要 this 指向目前元件,才能讀取state
屬性/呼叫setState()
方法,所以使用bind()
為匿名函數(shù)綁定目前執(zhí)行環(huán)境的 this,即目前元件。
你只要分辨下面幾個(gè)this就知道了。
1.bind(this)這個(gè)this指的是什麼。
2.不bind(this)時(shí),回呼執(zhí)行時(shí),函數(shù)裡的this指的是什麼。
3.bind(this)之後,回呼執(zhí)行時(shí),函數(shù)裡的this指的是什麼。