6

我有一个带有装饰器的 ES6 类。它有一个静态方法 foo。但是,当我尝试访问静态方法时,它是未定义的。

@withStyles(styles)
class MyComponent extends Component {
    static foo(){
        return "FOO";
    }
    render(){
        var x = MyComponent.foo; // x=undefined
    }
}

当我删除装饰器时,我可以访问静态方法。它不再是未定义的。

class MyComponent extends Component {
    static foo(){
        return "FOO";
    }
    render(){
        var x = MyComponent.foo; // x=foo()
    }
}

这个问题有解决方法吗?

4

1 回答 1

3

如果您使用babelwith es6,它可以像这样 (to es5) 进行转换:

var MyComponent = (function () {
  function MyComponent() {
    _classCallCheck(this, _MyComponent);
  }

  _createClass(MyComponent, null, [{
    key: 'foo',
    value: function foo() {
      return "FOO";
    }
  }]);

  var _MyComponent = MyComponent;
  Foo = withStyles(MyComponent) || MyComponent;
  return MyComponent;
})();

所以它的问题是withStyles(MyComponent)它将返回另一个显然没有您为原始类指定的静态方法的函数。

于 2016-01-20T15:30:17.207 回答