2017-06-29 59 views
2

我有一個基本的React應用程序,我想將一些常用的功能放入基本組件類中,並讓所有其他組件都從該類繼承以獲得對這些功能的訪問。我有這樣的:這個關鍵字在React基類中是未定義的

export class BaseComponent extends React.Component { 
    constructor() { 
     super(); 
     this.commonlyUsedMethod = this.commonlyUsedMethod.bind(this); 
    } 

    commonlyUsedMethod() { 
     let x = this.someValue; // <--- 'this' is undefined here 
    } 
} 

export class SomeComponent extends BaseComponent { 
    onButtonClick() { 
     super.commonlyUsedMethod(); 
    } 

    render() { 
     return whatever; 
    } 
} 

的問題是,當我打電話super.commonlyUsedMethod()從派生類,this.someValueBaseComponent.commonlyUsedMethod()炸燬因爲thisundefined。我在BaseComponent構造函數中調用this.commonlyUsedMethod.bind(this);,所以我不確定發生了什麼。

+1

你得到的實際錯誤信息是什麼?調用'onButtonClick'的代碼在哪裏?你記得把'onButtonClick'綁定到'this'嗎?爲什麼'onButtonClick'調用'super.commonlyUsedMethod'而不是'this.commonlyUsedMethod'? –

+0

我同意@JordanRunning。爲什麼'onButtonClick'正在調用'super.commonlyUserMethod'而不是'this.commonlyUserMethod' –

+1

@ whs.bsmith,所以你的組件不會擴展'React.Component'? – robertklep

回答

1

首先,我(和大多數React開發社區)不建議您使用繼承。 https://facebook.github.io/react/docs/composition-vs-inheritance.html

大多數使用情況下,您可以使用Higher Order Components或在JS文件中編寫函數並導入它來解決此問題。

如果你還想繼續做下去。
您需要綁定this當您將buttonClick聽衆

export class SomeComponent extends BaseComponent { 
    onButtonClick() { 
     super.commonlyUsedMethod(); 
    } 

    render() { 
     return <div onClick={this.onButtonClick.bind(this)}>Hello</div>; 
    } 
} 

這裏是它的工作示例。 https://www.webpackbin.com/bins/-Knp4X-n1RrHY1TIaBN-

更新:問題是不調用超級適當this,問題是與附加的的onClick偵聽器時沒有約束力適當this。感謝@Mayank指出。

+1

可以請你告訴我我在這裏失蹤,因爲它沒有'.call(this)'工作:https:/ /www.webpackbin.com/bins/-Knp7eAm845FhLPb_Mcf –

+0

你是對的。我現在意識到了。更新了答案 –

+0

這工作,謝謝你。調用'super.commonlyUsedMethod()'和'this.commonlyUsedMethod()'有區別嗎?在標準的OO練習中,你可以使用'this'。如果你在下面看到我的答案,它似乎工作。 – d512

0

所以我不知道這是否一個好的做法™,但我可以得到它通過調用this.someCommonMethod()而不是super.someCommonMethod(),像這樣的工作:

export class SomeComponent extends BaseComponent { 
    constructor() { 
     super(); 
     this.onButtonClick = this.onButtonClick.bind(this); 
    } 

    onButtonClick() { 
     this.commonlyUsedMethod(); <--- changed 'super' to 'this' 
    } 

    render() { 
     return whatever; 
    } 
} 

我足夠新反應和ES6不知道這是如何工作的。任何想法將不勝感激。

+0

但是如果你在那裏創建了相同的命名函數,你將不得不在繼承類中做超類 –