美文网首页react-this
ES6 箭头函数this, bind(this)的总结

ES6 箭头函数this, bind(this)的总结

作者: JackLee_ | 来源:发表于2017-04-08 11:28 被阅读0次

今天在撸代码的时候发现了 在react项目中this的猫腻。
我发现在使用React中 如果使用ES6的Class extends写法 如果onClick绑定一个方法 需要bind(this),
而使用React.createClass方法 就不需要.
那这又是为什么呢
上网查了资料发现:React.createClass 是es5的写法默认是绑定了bind方法,而es6中 新增加了class,绑定的方法需要绑定this,如果是箭头函数就不需要绑定this,用箭头的方式
第一种写法:

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

第二种写法:

    super(props);
    this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
    console.log(this);
}
render() {
    return (
        <div>
            <spanonClick={this.handleClick}>点击</span>
        </div>
    );
}

第三种写法:

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

相关文章

网友评论

    本文标题:ES6 箭头函数this, bind(this)的总结

    本文链接:https://www.haomeiwen.com/subject/horlattx.html