首页 > js bind(this) 问题

js bind(this) 问题

onSearchChange(event){
    this.props.dispatch(searchChange(event.target.value));
}

<SearchBar onSearchChange={ this.onSearchChange.bind(this) } />

经典问题,看几个同类型的不是特别明白,说下我的理解,求大手给指点下。
onSearchChange方法里边的this开始指向的是方法本身,不是全局,而在下边调用的时候,用bind把全局的this传进了onSearchChange方法,所以才能找到props属性。如果不用bind方法,onSearchChange中this.props是undefined。不知道我的理解对不对?


this不是静态绑定的,所以你这样的分析方法有问题。

判断this指向什么,只能在运行时判断。
拿你这个例子来说,之所以要bind,虽然你的代码没有贴全,我猜应该是用的class方式写的component吧?
class方式没有自动绑定event handler,换句话说,执行handler时,this没有指向component的instance,this.props也就不能用了。

更详细的react官方有说明:
https://facebook.github.io/react/docs/re...

另外,除了使用bind和=>函数之外,如果使用babel等工具,可以开启stage 0的class properties转换:

handleClick = (e) => {
    // do something
};
【热门文章】
【热门文章】