Reactjs React基类中未定义this关键字
我有一个基本的React应用程序,我想把一些常用的功能放到一个基本组件类中,并让我的所有其他组件从该类继承来访问这些功能。我有这个:Reactjs React基类中未定义this关键字,reactjs,inheritance,Reactjs,Inheritance,我有一个基本的React应用程序,我想把一些常用的功能放到一个基本组件类中,并让我的所有其他组件从该类继承来访问这些功能。我有这个: export class BaseComponent extends React.Component { constructor() { super(); this.commonlyUsedMethod = this.commonlyUsedMethod.bind(this); } commonlyUsed
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;
}
}
导出类BaseComponent扩展React.Component{
构造函数(){
超级();
this.commonlyUsedMethod=this.commonlyUsedMethod.bind(this);
}
常用方法(){
让x=this.someValue;//首先,我(以及大多数React开发者社区)不建议您使用继承
您拥有的大多数用例都可以使用JS文件中的函数或将其写入并导入来解决它
如果你还想继续做这件事。
连接按钮时,需要绑定此
export class SomeComponent extends BaseComponent {
onButtonClick() {
super.commonlyUsedMethod();
}
render() {
return <div onClick={this.onButtonClick.bind(this)}>Hello</div>;
}
}
导出类SomeComponent扩展了BaseComponent{
onButtonClick(){
super.commonlyUsedMethod();
}
render(){
回复你好;
}
}
下面是它的工作示例
更新:问题不在于使用正确的this
调用super,问题在于在连接onClick侦听器时没有绑定正确的this
。感谢@Mayank指出这一点。所以我不确定这是否是一个好的做法™, 但是我可以通过调用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;
}
}
导出类SomeComponent扩展了BaseComponent{
构造函数(){
超级();
this.onButtonClick=this.onButtonClick.bind(this);
}
onButtonClick(){
这个。常用的方法();您收到的实际错误消息是什么?调用onButtonClick
的代码在哪里?您是否记得将onButtonClick
绑定到this
?为什么onButtonClick
调用super.commonlyUsedMethod
而不是这个.commonlyUsedMethod
?我同意@jordanlunning.WhyonButtonClick
正在调用super.commonlyUserMethod
而不是这个.commonlyUserMethod
@whs.bsmith所以你的组件不会扩展React.Component
?@robertklep这不是我的意思。我的意思是我不会扩展我自己的组件。我误解了这篇文章。你能告诉我我是什么吗在这里使用,因为它在没有的情况下工作。调用(此)
:你是对的。我现在意识到了。更新了答案。谢谢你。调用super.commonlyUsedMethod()
和this.commonlyUsedMethod()有什么区别吗
?在标准的OO实践中,您将使用这个
。如果您在下面看到我的答案,这似乎是可行的。但是如果您在继承的类中创建了相同的命名函数,您必须在继承的类中执行super