因爲類的方法默認不會綁定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轉譯性能