【发布时间】:2017-04-11 16:02:50
【问题描述】:
如何绑定this 和transform-decorators-legacy Babel 插件?
例如,我有一些简单的装饰器。装饰器工作,但 this 在组件的方法上未定义。
fucntion myDecorator(target, name, descriptor) {
var oldValue = descriptor.value;
descriptor.value = function() {
...// Doing some stuff here I need the decorator for
...// (for example logging on every method call)
return oldValue.apply(null, arguments);
};
return descriptor;
}
class MyClass extends React.Component {
@myDecorator
myMethod() {
...// this.props... is unavailable here(`this` is undefined)
}
}
如果我尝试将 @myDecorator 与一些 @autobind 装饰器一起使用,我会得到
TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute,因为
数据描述符是具有值的属性,该值可能是可写的,也可能是不可写的。访问器描述符是由一对 getter-setter 函数描述的属性。描述符必须是这两种风格之一;不能两者兼有。
在我的示例中,我不能使用 value() 和 get()。
在构造函数 (this.myMethod = thid.myMethod.bind(this)) 中绑定似乎也没有帮助,因为您绑定了未修饰的方法。
【问题讨论】:
标签: javascript reactjs decorator ecmascript-next