react合成事件的三种绑定方式bind

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35388564/article/details/76040332

在使用ES6 classes或者纯函数时,不存在自动绑定,需要我们手动实现this的绑定。


一 bind方法。这个方法可以绑定事件处理器内的this,并可以向事件处理器中传递参数,例:

class App extends Component{
    handleClick(e,arg){
        console.log(e,arg);
    }
    render(){
        return<button onClick={this.handleClick.bind(this,'test')}>Test</button>;
    }
}
若不传参即可写为
this.handleClick.bind(this)
另外stage 0草案中提供了一个便捷的方案——双冒号语法,例:

<button onClick={::this.handleClick}>Test</button>


二 构造器内声明,优点为仅需要进行一次绑定,不需要每次调用时去执行绑定。

class App extends Component{
    constructor(props){
        super(props);
        this.handleClick=this.handleClick.bind(this)
    }
    handleClick(){
        console.log("ok")
    }
    render(){
        return(
            <button onClick={this.handleClick}>按钮</button>
        )
    }
}



三 箭头函数,自动绑定了定义此函数作用域的this。

class App extends Component{
    const handleClick=(e)=>{
        console.log(e);
    }
    render(){
        return<button onClick={this.handleClick}>Test</button>;
    }
}

class App extends Component{
    handleClick(e){
        console.log(e);
    }
    render(){
        return<button onClick={()=>this.handleClick()}>Test</button>;
    }
}



猜你喜欢

转载自blog.csdn.net/qq_35388564/article/details/76040332