繁体   English   中英

在React中使用方法装饰器时将其绑定

[英]Bind this when using method decorators in React

如何将thistransform-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 TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute ,因为

数据描述符是具有值的属性,该值可以写也可以不写。 访问器描述符是由一对getter-setter函数描述的属性。 描述符必须是这两种形式之一。 不能两者兼有。

在我的示例中,我不能使用value()get()

绑定构造函数( this.myMethod = thid.myMethod.bind(this) )似乎也没有用,因为您绑定了未修饰的方法。

.bind装饰方法不是问题。

但是,您错过了一些东西。 即使你是.bindmyMethod你的内部constructor的类,当你调用它,没有来自哪里,不管myDecorator修改执行范围。

oldValue.apply(null, arguments)

基本上,您将目标范围( MyClass )替换为null

所以您想要的是:

oldValue.apply(this, arguments)

看到这个小提琴: http : //jsfiddle.net/free_soul/0n6v1dtp/

这就是我设法解决的方法:使用提到的@autobind装饰器中的代码:

function myDecorator(target, key, descriptor) {
    let fn = descriptor.value;

    return {
        configurable: true,

        get() {
            let boundFn = fn.bind(this);
            Reflect.defineProperty(this, key, {
                value: boundFn,
                configurable: true,
                writable: true
            });

            return function() {
                ...// Doing some stuff here I need the decorator for
                ...// (for example logging on every method call)
                return boundFn.apply(this, arguments)
            };
        }
    };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM