我有以下窗口小部件类:
var Widget = React.createClass({
statics: {title: "a title"},
...
});有没有办法在类的方法中访问静态的标题(使用this)?例如:
render: function() {
return <div>{this.title}</div>;
}发布于 2015-08-13 02:54:10
您可以从this.constructor的组件中访问静态
因此,在这种情况下,它将是:
this.constructor.title发布于 2015-02-26 06:25:21
直接的答案是:
React.createClass({
title: 'a title',
render: function() {
return <div>{this.title}</div>;
}
});或者:
React.createClass({
componentWillMount: function(){
this.title = 'a title';
},
render: function() {
return <div>{this.title}</div>;
}
});但说真的..。为什么不直接使用变量呢?
var TITLE = 'a title';
React.createClass({
render: function() {
return <div>{TITLE}</div>;
}
});发布于 2015-02-26 03:31:34
React类的statics对象是一种定义静态方法(即不需要任何上下文即可运行的方法)的方法。也就是说,从this调用静态方法是没有意义的。
看起来您正在寻找一个“静态”属性(即,不可变的)。因此,您应该像在render()上使用this.props.title一样使用它。要设置title的值,您应该执行<Widget title='a title'/>。值得一提的是,您可以通过定义getDefaultProps方法来设置默认属性。
https://stackoverflow.com/questions/28725125
复制相似问题