React 使用ES6+语法时 事件绑定疑惑

在使用React中 如果使用ES6的Class extends写法 如果onClick绑定一个方法 需要bind(this),
而使用React.createClass方法 就不需要.
请问这是为什么呢

阅读 19k
8 个回答

React自动绑定
Autobinding: When creating callbacks in JavaScript, you usually need to explicitly bind a method to its instance such that the value of this is correct. With React, every method is automatically bound to its component instance. React caches the bound method such that it's extremely CPU and memory efficient. It's also less typing!

第一种

_handleClick(e) {
    console.log(this);
}
render() {
    return (
        <div>
            <h1 onClick={this._handleClick.bind(this)}>点击</h1>
        </div>
    );
}

第二种

constructor(props) {
    super(props);
    this._handleClick = this._handleClick.bind(this)
}
_handleClick(e) {
    console.log(this);
}
render() {
    return (
        <div>
            <h1 onClick={this._handleClick}>点击</h1>
        </div>
    );
}

第三种

_handleClick = (e) => {
    // 使用箭头函数(arrow function)
    console.log(this);
}
render() {
    return (
        <div>
            <h1 onClick={this._handleClick}>点击</h1>
        </div>
    );
}

注释: 箭头函数需要在 编译的时候, 配置 支持 箭头函数参考文章
http://babeljs.io/blog/2015/06/07/react-on-es6-plus/
http://babeljs.io/blog/2015/10/31/setting-up-babel-6/

在props里使用 onClick={ this.handleClick.bind(this) } 或者 onClick={ (e) => this.handleClick(e) } 或者 onClick={ ::this.handleClick } 都会产生性能问题,所以现在eslint在语法检查时就会阻止这几种写法,问题原因是每一次render的时候如果遇到这些写法,都会重新用handleClick函数与this去绑定从而重新创建一个新的函数,影响性能。 如果使用下面的写法则不会每次都创建:

// 1. 
constructor() {
    this.handleClick = this.handleClick.bind(this);
}
handleClick(e) { /* ... */ }
// 2. 
handleClick = (e) => { /* ... */ };

确实有很多问题,react+ES6。楼上贴出来是一部分,另外官网也介绍了其他局限,比如initialState mixin propTypes defaultPros等都要注意。
所以我觉得要么就用creatClass省事

还是建议使用createClass因为mixin等有用的功能无法使用在react.component定义的组件。

新手上路,请多包涵

第四种方式

_handleClick() {
    console.log(this);
}
render() {
    return (
        <div>
            <h1 onClick={::this._handleClick}>点击</h1>
        </div>
    );
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题