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

送分小仙女□ 提交于 2019-12-10 13:39:41

问题


I have an ES6 class with a decorator. It has a static method foo. However when I try to access the static method, its undefined.

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

When I remove the decorator I can access the static method. Its no longer undefined.

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

Is there a workaround for this issue?


回答1:


If you're using babel with es6, it could be transpiled like that (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;
})();

So its problem is that withStyles(MyComponent) will return another function which obviously doesn't have static methods you specified for original class.



来源:https://stackoverflow.com/questions/34901860/static-method-is-undefined-in-es6-classes-with-a-decorator-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!