使用React.createClass
會自動綁定每個方法的this到當(dāng)前組件,但使用ES6 class
關(guān)鍵字時,這種自動綁定功能就沒有,需要手動綁定this
。不然的話,經(jīng)常出現(xiàn)this
是undefined
的現(xiàn)象。
比如下面的test2
中的this
指向就不正確了。
import React from 'react';
export default class App extends React.Component{
constructor(props){
super(props);
}
render(){
this.test1();
return (
<div onClick={ this.test2 }>abc</div>
)
}
test1(){
console.log(this); // App
}
test2(){
console.log(this); // null
}
}
解決方案一:采用箭頭函數(shù)
箭頭函數(shù)將this和函數(shù)定義時的上下文綁定,能達(dá)到期望的效果。
render() {
this.test1(); // 這里不存在歧義,可以直接用
return (
<div onClick={ () => this.test2() }>abc</div> // 這里用箭頭函數(shù),讓this和定義時的上下文綁定,這里是App
)
}
解決方案二:在回調(diào)響應(yīng)的地方手動綁定
render() {
this.test1(); // 這里不存在歧義,可以直接用
return (
<div onClick={ this.test2.bind(this) }>abc</div> // 手動綁定;綁定當(dāng)前組件App,而不是執(zhí)行時的<div>標(biāo)簽
)
}
解決方案三:構(gòu)造函數(shù)中手動綁定
constructor(props) {
super(props);
this.test2 = this.test2.bind(this); // 將this和當(dāng)前組件綁定
}
React.createClass
估計采用的就是這種方案,構(gòu)造函數(shù)將所有的function成員都自動綁定一下。
選擇的方案
- 大多數(shù)時候可以選擇方案一,用箭頭函數(shù),比較簡潔;
- 如果箭頭函數(shù)不起左右,可以選擇bind的方式;