react事件this指向 this丢失
react在事件监听时可能会导致this指向丢失,以下几种方式可以修正这个问题
1.嵌套箭头函数
<button onClick={(e)=>this.fn1(e)}>按钮fn1</button>
箭头函数可以修正fn1函数内部的this指向,但如使用事件对象的话需要显式传递事件对象参数
2.监听的函数是箭头函数
<button onClick={this.fn2}>按钮fn2</button> //fn2 fn2=(e)=>{ console.log("fn2 箭头函数") console.log(this) console.log(e.target) }
3.监听时使用bind
<button onClick={this.cl.bind(this)}>按钮cl</button>
4.构造函数预先绑定bind
<button onClick={this.fn}>按钮fn</button> // class APP extends React.Component{ constructor() { super(); this.fn=this.fn.bind(this) } fn(e){ console.log("方法") console.log(this) console.log(e.target) } render() { return ( <button onClick={this.fn}>按钮fn</button> ) }
构造函数绑定权重较高,如果构造函数绑定之后,在jsx中再次使用bind方法绑定别的对象,仍会是构造函数绑定的this