Tza*_*ach 15 javascript reactjs
我有以下小部件类:
var Widget = React.createClass({
statics: {title: "a title"},
...
});
Run Code Online (Sandbox Code Playgroud)
有没有办法在class'es方法(使用this)中访问标题static ?例如:
render: function() {
return <div>{this.title}</div>;
}
Run Code Online (Sandbox Code Playgroud)
Geo*_*lah 18
您可以从以下组件中访问组件中的静态this.constructor:
所以在这种情况下它将是:
this.constructor.title
Run Code Online (Sandbox Code Playgroud)
直接答案:
React.createClass({
title: 'a title',
render: function() {
return <div>{this.title}</div>;
}
});
Run Code Online (Sandbox Code Playgroud)
要么:
React.createClass({
componentWillMount: function(){
this.title = 'a title';
},
render: function() {
return <div>{this.title}</div>;
}
});
Run Code Online (Sandbox Code Playgroud)
但真的......为什么不只是使用变量?
var TITLE = 'a title';
React.createClass({
render: function() {
return <div>{TITLE}</div>;
}
});
Run Code Online (Sandbox Code Playgroud)
staticsReact类的对象是一种定义静态方法的方法(即,不需要运行任何上下文的方法).话虽如此,从静态方法调用是没有意义的this.
看起来你正在寻找一个"静态"属性(即不可变).所以,你应该像this.props.title上一样使用它render().要设置标题的值,你应该这样做<Widget title='a title'/>.值得一提的是,您可以通过定义getDefaultProps方法来设置默认属性.