bind.png
react中避免不了经常需要对this进行操作,而事件默认react是不被bind到当前react实例上的,需要手动进行绑定,绑定的方式有许多种,在此进行简要小结及对不同的方法的优劣进行对比。
使用React.createClass
可参考官方文档说明,使用react.createclass进行组件创建将自动绑定this,只需简单写onChange={this.handleChange}
React.createClass, React autobinds all functions to this
render中绑定-bind(this)
在render函数中,定义事件的同时对this进行绑定
onChange={this.handleChange.bind(this)}
该方法的缺陷是由于是在渲染中进行绑定,即生成vnode过程中进行绑定,对性能有一定影响,但大多可忽略不计。 该方法对性能的详细影响可以参考这里.
render中绑定-使用箭头函数
在render函数中,定义事件的时候使用箭头函数
onChange={e => this.handleChange(e)}
在构造函数中绑定
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
被react官方推荐的写法
class声明中使用箭头函数
handleChange = () => {
// call this function from render
// and this.whatever in here works fine.
};
依赖于新的class标准提案,要单独使用需要使用transform-class-properties or enable stage-2 in Babel.
小结
React_bind_this.png
更多可参考