search

Home  >  Q&A  >  body text

javascript - A question about react

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中文网PHP中文网2751 days ago765

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-06-15 09:25:44

    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.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-15 09:25:44

    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.

    reply
    0
  • Cancelreply