亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - A question about react
PHP中文網(wǎng)
PHP中文網(wǎng) 2017-06-15 09:23:44
0
2
834

The following is a simple dynamic effect written in react, but the details are unclear. Why do we need to add bind(this) at the end of the timer? What is its function? What knowledge point do I lack that makes me unclear about adding 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)證高級PHP講師

reply all(2)
大家講道理

Two knowledge points:

  • bind()

  • this points to

Specifically for this example, if you directly call the anonymous function defined in setInterval without using bind(), this inside the function points to the window object. Inside the anonymous function, it is obvious that this needs to point to the current component in order to read the state attribute/call the setState() method, so use bind() to bind the anonymous function to this of the current execution environment, that is, the current component.

phpcn_u1582

You only need to distinguish the following several this to know.

1.bind(this)What does this refer to?
2. When bind(this) is not used, what does this in the function refer to when the callback is executed.
3. After bind(this), when the callback is executed, what does this in the function refer to.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template