react关于事件绑定this的四种方式
发布时间:2020-12-15 06:32:37 所属栏目:百科 来源:网络整理
导读:在react组件中,每个方法的上下文都会指向该组件的实例,即自动绑定this为当前组件,而且react还会对这种引用进行缓存,以达到cpu和内存的最大化。在使用了es6 class或者纯函数时,这种自动绑定就不复存在了,我们需要手动实现this的绑定 以下是几种绑定的方
在react组件中,每个方法的上下文都会指向该组件的实例,即自动绑定this为当前组件,而且react还会对这种引用进行缓存,以达到cpu和内存的最大化。在使用了es6 class或者纯函数时,这种自动绑定就不复存在了,我们需要手动实现this的绑定 bind方法 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> ); } } 构造函数内绑定 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> ); } } 箭头函数绑定 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,大家一起讨论,一起进步,后续更新中... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容