我有一個基本的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.someValue
內BaseComponent.commonlyUsedMethod()
炸燬因爲this
是undefined
。我在BaseComponent
構造函數中調用this.commonlyUsedMethod.bind(this);
,所以我不確定發生了什麼。
你得到的實際錯誤信息是什麼?調用'onButtonClick'的代碼在哪裏?你記得把'onButtonClick'綁定到'this'嗎?爲什麼'onButtonClick'調用'super.commonlyUsedMethod'而不是'this.commonlyUsedMethod'? –
我同意@JordanRunning。爲什麼'onButtonClick'正在調用'super.commonlyUserMethod'而不是'this.commonlyUserMethod' –
@ whs.bsmith,所以你的組件不會擴展'React.Component'? – robertklep