React-事件绑定

一、bind方法

这个方法可以绑定事件处理器内的this,并可以向事件处理器中传递参数(自带的event是在参数的最后一位)
class App extends Component{
    handleClick(e,arg){
        console.log(e,arg);
    }
    render(){
        return<button onClick={this.handleClick.bind(this,'test')}>Test</button>;
    }
}

不传参: onClick={this.handleClick.bind(this)}

二、构造器内声明

优点为仅需要进行一次绑定,不需要每次调用时去执行绑定
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>;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容