Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 480
GunnerFan Avatar asked Jan 20 '16 13:01

GunnerFan


1 Answers

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.

like image 74
oleh.meleshko Avatar answered Oct 28 '22 00:10

oleh.meleshko