问题
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