国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

javascript - 關(guān)於react裡的一個(gè)疑問(wèn)
PHP中文網(wǎng)
PHP中文網(wǎng) 2017-06-15 09:23:44
0
2
835

下面是一段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
);
PHP中文網(wǎng)
PHP中文網(wǎng)

認(rèn)證高級(jí)PHP講師

全部回覆(2)
大家講道理

兩個(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,即目前元件。

phpcn_u1582

你只要分辨下面幾個(gè)this就知道了。

1.bind(this)這個(gè)this指的是什麼。
2.不bind(this)時(shí),回呼執(zhí)行時(shí),函數(shù)裡的this指的是什麼。
3.bind(this)之後,回呼執(zhí)行時(shí),函數(shù)裡的this指的是什麼。

最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板