react关于事件绑定this的四种方式

在react组件中,每一个方法的上下文都会指向该组件的实例,即自动绑定this为当前组件,并且react还会对这种引用进行缓存,以达到cpu和内存的最大化。在使用了es6 class或者纯函数时,这种自动绑定就不复存在了,咱们须要手动实现this的绑定 如下是几种绑定的方法:react

bind方法

直接绑定是bind(this)来绑定,可是这样带来的问题是每一次渲染是都会从新绑定一次bind;es6

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
        };
    }

    del(){
        console.log('del')
    }

    render() {
        return (
            <div className="home">
                <span onClick={this.del.bind(this)}></span>
            </div>
        );
    }
}
复制代码

构造函数内绑定

在构造函数 constructor 内绑定this,好处是仅须要绑定一次,避免每次渲染时都要从新绑定,函数在别处复用时也无需再次绑定缓存

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.state = {

        };
        this.del=this.del.bind(this)
    }

    del(){
        console.log('del')
    }

    render() {
        return (
            <div className="home">
                <span onClick={this.del}></span>
            </div>
        );
    }
}
复制代码

::(双冒号)不能传参

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.state = {

        };
    }

    del(){
        console.log('del')
    }

    render() {
        return (
            <div className="home">
                <span onClick={::this.del}></span>
            </div>
        );
    }
}
复制代码

箭头函数绑定

箭头函数不只是函数的'语法糖',它还自动绑定了定义此函数做用域的this,由于咱们不须要再对它们进行bind方法:bash

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.state = {

        };

    }

    del=()=>{
        console.log('del')
    }

    render() {
        return (
            <div className="home">
                <span onClick={this.del}></span>
            </div>
        );
    }
}
复制代码

以上几种方法均可以实现this绑定,使用那种各自的习惯; 但愿你们喜欢,也但愿你们指点错误,也能够加入qq群439667347,你们一块儿讨论,一块儿进步,后续更新中...函数

相关文章
相关标签/搜索