React事件綁定
由於類的方法默認不會綁定this,因此在調用的時候如果忘記綁定,this的值將會是undefined。
通常如果不是直接調用,應該爲方法綁定this。綁定方式有以下幾種:
1. 在構造函數中使用bind綁定this
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>
);
}
}
2. 在調用的時候使用bind綁定this
class Button extends React.Component {
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>
Click me
</button>
);
}
}
3. 在調用的時候使用箭頭函數綁定this
class Button extends React.Component {
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={()=>this.handleClick()}>
Click me
</button>
);
}
}
4. 使用屬性初始化器語法綁定this(實驗性)
class Button extends React.Component {
handleClick=()=>{
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
比較
方式2和方式3都是在調用的時候再綁定this。
- 優點:寫法比較簡單,當組件中沒有state的時候就不需要添加類構造函數來綁定this
- 缺點:每一次調用的時候都會生成一個新的方法實例,因此對性能有影響,並且當這個函數作爲屬性值傳入低階組件的時候,這些組件可能會進行額外的重新渲染,因爲每一次都是新的方法實例作爲的新的屬性傳遞。
方式1在類構造函數中綁定this,調用的時候不需要再綁定
- 優點:只會生成一個方法實例,並且綁定一次之後如果多次用到這個方法也不需要再綁定。
- 缺點:即使不用到state,也需要添加類構造函數來綁定this,代碼量多一點。。。
方式4:利用屬性初始化語法,將方法初始化爲箭頭函數,因此在創建函數的時候就綁定了this。
優點:創建方法就綁定this,不需要在類構造函數中綁定,調用的時候不需要再作綁定。結合了方式1、方式2、方式3的優點
缺點:目前仍然是實驗性語法,需要用babel轉譯
總結
方式1是官方推薦的綁定方式,也是性能最好的方式。方式2和方式3會有性能影響並且當方法作爲屬性傳遞給子組件的時候會引起重渲問題。方式4目前屬於實驗性語法,但是是最好的綁定方式,需要結合bable轉譯