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

Using React.js statics inside class methods

我有以下小部件 class:

var Widget = React.createClass({
    statics: {title: "a title"},
    ...
});

有没有办法在 class 的方法(使用 this)中访问静态标题?例如:

render: function() {
    return <div>{this.title}</div>;
}

React Class 的 statics object 是一种定义静态方法的方法(即不需要任何上下文的方法 运行)。也就是说,从 this.

调用静态方法没有意义

您似乎在寻找 "static" 属性(即 non-mutable)。所以,你应该像 this.props.title on render() 那样使用它。要设置标题的值,你应该做<Widget title='a title'/>。值得一提的是,您可以通过定义 getDefaultProps 方法来设置默认属性。

有关 statics and about props 的更多信息,请参见 React 文档。

直接回答:

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>;
    }
});

您可以从 this.constructor 的组件内访问静态:

所以在这种情况下它将是:

this.constructor.title