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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28725125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:26:43  来源:igfitidea点击:

Using React.js statics inside class methods

javascriptreactjs

提问by Tzach

I have the following widget class:

我有以下小部件类:

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

Is there a way of accessing the title static inside the class'es methods (using this)? For example:

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

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

回答by Geoffrey Abdallah

You can access a static from within the component from this.constructor:

您可以从以下组件中访问静态this.constructor

so in this case it would be:

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

this.constructor.title

回答by Brigand

The direct answer:

直接回答:

React.createClass({
    title: 'a title',
    render: function() {
        return <div>{this.title}</div>;
    }
});

Or:

或者:

React.createClass({
    componentWillMount: function(){
        this.title = 'a title';
    },
    render: function() {
        return <div>{this.title}</div>;
    }
});

But really... why not just use a variable?

但真的......为什么不只使用一个变量?

var TITLE = 'a title';

React.createClass({
    render: function() {
        return <div>{TITLE}</div>;
    }
});

回答by cyberglot

The staticsobject of a React Class is a way to define static methods (i.e., methods that don't need any context to run). That being said, it doesn't make sense to call a static method from this.

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

It looks like you're looking for a "static" property (i.e., non-mutable). So, you should use it like this.props.titleon render(). To set the value of title, you should do <Widget title='a title'/>. It worths mentioning that you can set default properties, by defining the getDefaultPropsmethod.

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

More about staticsand about propson React's doc.

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