6 个回答

题主想知道的应该是这里为什么要用bind。

  1. 首先bind就是改变函数运行时的this,详细请看bind

  2. 你的代码中调用了setInterval(fun, time),其实等同于window.setInterval(fun, time)

  3. 如果没调用bind(this),那么传入setInterval中的fun的this指向是setInterval的调用者window对象

  4. 给函数bind(this),这里的this指向就是componentDidMount()中的this也就是这个react对象,这样才能够正确访问react属性方法this.state,this.setState等

绑定this.

clipboard.png

就是把外面(componentDidMount)的this传到内部(timer),跟很多人喜欢在外面定义一个that,里面用that来指向外部的this是一个道理。这个跟react没有关系,是js的基础,你可以去看看js的bind, call, apply。

bind可以改变函数内部this的指向,此外还可以想函数传递数据,参数arguments
例如

onChange={this.changeValue.bind(this,'value')}

这个的话,这个函数就可以这样写了

changeValue(str){
console.log(str)  //'value'
}

文档上是这么写的

Function.prototype.bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

大概意思就是绑定函数调用时的this.
ECMAScript 5.1增加的特性,与React无关

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏