javascript 如何在我的 React Component 类中拥有类范围的常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47101042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I have class-wide constant in my React Component class?
提问by notalentgeek
Usually I do this:
通常我这样做:
var tagSymbols = Object.freeze([
'!',
'+',
'@'
]);
But then I know there is constfrom Babel (?).
但后来我知道有const来自 Babel (?)。
const tagSymbols = Object.freeze([
'!',
'+',
'@'
]);
Both return the same error:
两者都返回相同的错误:
Syntax error: Unexpected token (4:6)
2 |
3 | class GeneralToDoListInput extends Component {
> 4 | var tagSymbols = Object.freeze([
| ^
5 | '!',
6 | '+',
7 | '@'
Syntax error: Unexpected token (5:8)
3 | class GeneralToDoListInput extends Component {
4 |
> 5 | const tagSymbols = Object.freeze([
| ^
6 | '!',
7 | '+',
8 | '@'
回答by Felix Kling
You cannot put variable declarations inside a class body. That's just not allowed by the language. In ES6, the structure of a class declaration is basically
您不能将变量声明放在类体内。这是语言所不允许的。在 ES6 中,类声明的结构基本上是
class Foo() {
method1() {}
method2() {}
...
}
The simplest solution would be to put the variable declaration outside of the class:
最简单的解决方案是将变量声明放在类之外:
const tagSymbols = ...:
class GeneralToDoListInput extends Component {
...
}
Any code inside the class/module can access tagSymbols.
类/模块中的任何代码都可以访问tagSymbols.
If it really has to be a class property you can either define a static getter:
如果它真的必须是一个类属性,你可以定义一个静态 getter:
class GeneralToDoListInput extends Component {
static get tagSymbols() {
return Object.freeze(...);
}
}
Or assign it to the class after the declaration:
或者在声明后将其分配给类:
class GeneralToDoListInput extends Component {
...
}
GeneralToDoListInput.tagSymbols = ...;

