React:引入class關(guān)鍵字后this的綁定問題

使用React.createClass會自動綁定每個方法的this到當(dāng)前組件,但使用ES6 class關(guān)鍵字時,這種自動綁定功能就沒有,需要手動綁定this。不然的話,經(jīng)常出現(xiàn)thisundefined的現(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的方式;

參考文章

React綁定this的三種方式

理解React中es6方法創(chuàng)建組件的this

React中使用ES6 class的this指向?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容