在类方法中使用React.js静态

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)

  • 这记录了吗?如果是这样我们可以获得链接? (3认同)

Bri*_*and 8

直接答案:

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)

  • 请注意,在示例#3中,"TITLE"将是静态的,并在类的每个实例之间共享. (2认同)

cyb*_*lot 6

staticsReact类的对象是一种定义静态方法的方法(即,不需要运行任何上下文的方法).话虽如此,从静态方法调用是没有意义的this.

看起来你正在寻找一个"静态"属性(即不可变).所以,你应该像this.props.title上一样使用它render().要设置标题的值,你应该这样做<Widget title='a title'/>.值得一提的是,您可以通过定义getDefaultProps方法来设置默认属性.

更多关于静态和关于React的文档的道具.