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

Wit*_*ult 2 ecmascript-6 reactjs

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

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

但是对于如下定义的反应组件需要相同的

class MyComponent extends Component{ ... }
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*imo 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'
Run Code Online (Sandbox Code Playgroud)

有关MDN的来源和更多信息