因为类的方法默认不会绑定this,所以在调用的时候若是忘记绑定,this的值将会是undefined。
一般若是不是直接调用,应该为方法绑定this。绑定方式有如下几种:javascript
class Button extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
class Button extends React.Component { handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick.bind(this)}> Click me </button> ); } }
class Button extends React.Component { handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={()=>this.handleClick()}> Click me </button> ); } }
class Button extends React.Component { handleClick=()=>{ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
方式2和方式3都是在调用的时候再绑定this。java
方式1在类构造函数中绑定this,调用的时候不须要再绑定babel
方式4:利用属性初始化语法,将方法初始化为箭头函数,所以在建立函数的时候就绑定了this。
优势:建立方法就绑定this,不须要在类构造函数中绑定,调用的时候不须要再做绑定。结合了方式1、方式2、方式3的优势
缺点:目前仍然是实验性语法,须要用babel转译函数
方式1是官方推荐的绑定方式,也是性能最好的方式。方式2和方式3会有性能影响而且当方法做为属性传递给子组件的时候会引发重渲问题。方式4目前属于实验性语法,可是是最好的绑定方式,须要结合bable转译性能