如何在React es6组件中定义静态?

时间:2016-07-14 18:47:21

标签: reactjs ecmascript-6

我想在React es6组件中定义静态。我知道它是如何完成以下组件

var MyComponent = React.createClass({
  statics: {
    customMethod: function(foo) {
      return foo === 'bar';
    }
  },
  render: function() {
  }
});

但是对于下面定义的反应组件

需要相同的
class MyComponent extends Component{ ... }

此外,我想从MyComponent将要实例化的地方调用该方法。

1 个答案:

答案 0 :(得分:5)

您可以使用static关键字在ES6类中创建静态成员变量:

class StaticMethodCall {
    static staticMethod() {
        return 'Static method has been called';
    }
    static anotherStaticMethod() {
        return this.staticMethod() + ' from another static method';
    }
}
StaticMethodCall.staticMethod(); 
// 'Static method has been called'

StaticMethodCall.anotherStaticMethod(); 
// 'Static method has been called from another static method'

Source and more info on MDN