ES6(React)中的bind(this)详解

初心-杨瑞超个人博客诚邀您加入qq群(IT-程序猿-技术交流群):757345416

探讨问题:
在使用React中 如果使用ES6的Class extends写法 如果onClick绑定一个方法,需要bind(this),而使用React.createClass方法 就不需要。
解析:
React.createClass 是ES5 的写法默认绑定了 bind 写法。
在 ES6 中新增了class,绑定的方法需要绑定 this,如果是箭头函数就不需要绑定 this。

方法一:

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

方法二:

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

第二种另一种形式:

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

第三种:

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

文章到此结束,希望对你的学习有帮助!

猜你喜欢

转载自blog.csdn.net/qq_42817227/article/details/82689047