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

Using React.js statics inside class methods

本文关键字:React js 静态 类方法      更新时间:2024-05-09

我有以下小部件类:

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

有没有一种方法可以访问类的方法中的静态标题(使用this)?例如:

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

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

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

this.constructor.title

直接答案:

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>;
    }
});
React class的statics对象是定义静态方法(即不需要任何上下文来运行的方法)的一种方式。也就是说,从this调用静态方法是没有意义的。

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

更多关于静态和道具的信息,请参阅React的文档。