我有一个静态 getter,可以获取类内的变量。然而,getter 返回未定义——同时通过 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 是如何工作的)
最佳答案
I have a static getter …
这正是问题所在。它不应该是静态
。您正在声明 ParentClass.title
而不是实例属性。
关于javascript - Getter 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45069047/