我有一个静态getter,它抓取一个类中的变量。但是,getter返回undefined - 而通过this._title
获取变量效果很好。
import React, { Component } from 'react';
class ParentClass extends Component {
_title = "Parent Class";
static get title() {
return this._title;
}
}
export default class ChildClass extends ParentClass {
_title = "Child Class";
render() {
return (
<div>
<p>{"By Variable: " + this._title}</p>
<p>{"By Getter: " + this.title}</p>
</div>
)
}
}
这是渲染的结果: Result
更新
这是我的应用,或者试图从外部访问该类的内容:
import React, { Component } from 'react';
import ChildClass from './pages/Status';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={byu} className="App-logo" alt="logo" />
<h2>Welcome to the P&G System Status Utility</h2>
</div>
<p className="App-intro">
To get started, select a server:
</p>
<p>{"Outside Title: " + ChildClass.title}</p>
<p>{"Outside Description: " + ChildClass.description}</p>
<p>{"Outside Author: " + ChildClass.author}</p>
<ChildClass/>
<Scanner/>
</div>
);
}
}
export default App;
这是ChildClass(和它扩展的ParentClass)
import React, { Component } from 'react';
class ParentClass extends Component {
_title = "Debug";
_description = "Debug Description";
_author = "Arbiter";
get title() {
return this._title;
}
set title(value) {
this._title = value;
}
get description() {
return this._description;
}
set description(value) {
this._description = value;
}
get author() {
return this._author;
}
set author(value) {
this._author = value;
}
}
export default class ChildClass extends ParentClass {
title = "Child Class";
render() {
return (
<div>
<p>{"Title Inside: " + this.title}</p>
<p>{"Description Inside: " + this.description}</p>
<p>{"Author Inside: " + this.author}</p>
</div>
)
}
}
结果如下:enter image description here
(我完全不知道StackOverflow是如何工作的)
答案 0 :(得分:2)
我有静电吸气剂......
这正是问题所在。它不应该是static
。您声明ParentClass.title
而不是实例属性。