javascript 在类方法中使用 React.js 静态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28725125/
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
Using React.js statics inside class methods
提问by Tzach
I have the following widget class:
我有以下小部件类:
var Widget = React.createClass({
statics: {title: "a title"},
...
});
Is there a way of accessing the title static inside the class'es methods (using this
)? For example:
有没有办法访问类的方法中的静态标题(使用this
)?例如:
render: function() {
return <div>{this.title}</div>;
}
回答by Geoffrey Abdallah
You can access a static from within the component from this.constructor
:
您可以从以下组件中访问静态this.constructor
:
so in this case it would be:
所以在这种情况下,它将是:
this.constructor.title
回答by Brigand
The direct answer:
直接回答:
React.createClass({
title: 'a title',
render: function() {
return <div>{this.title}</div>;
}
});
Or:
或者:
React.createClass({
componentWillMount: function(){
this.title = 'a title';
},
render: function() {
return <div>{this.title}</div>;
}
});
But really... why not just use a variable?
但真的......为什么不只使用一个变量?
var TITLE = 'a title';
React.createClass({
render: function() {
return <div>{TITLE}</div>;
}
});
回答by cyberglot
The statics
object of a React Class is a way to define static methods (i.e., methods that don't need any context to run). That being said, it doesn't make sense to call a static method from this
.
statics
React 类的对象是一种定义静态方法(即不需要任何上下文即可运行的方法)的方式。话虽如此,从this
.
It looks like you're looking for a "static" property (i.e., non-mutable). So, you should use it like this.props.title
on render()
. To set the value of title, you should do <Widget title='a title'/>
. It worths mentioning that you can set default properties, by defining the getDefaultProps
method.
看起来您正在寻找“静态”属性(即非可变属性)。所以,你应该像this.props.title
on一样使用它render()
。要设置 title 的值,您应该执行<Widget title='a title'/>
. 值得一提的是,您可以通过定义getDefaultProps
方法来设置默认属性。