静态方法在 ES6 类中未定义,在 reactjs 中有一个装饰器

Static method is undefined in ES6 classes with a decorator in reactjs

本文关键字:有一个 reactjs 未定义 ES6 静态方法      更新时间:2023-09-26

我有一个带有装饰器的 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()
    }
}

此问题是否有解决方法?

如果你将babeles6一起使用,它可以像这样翻译(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)将返回另一个函数,该函数显然没有您为原始类指定的静态方法。

相关文章: