我有一个基本的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