Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React中使用方法装饰器时绑定此_Javascript_Reactjs_Decorator_Ecmascript Next - Fatal编程技术网

Javascript 在React中使用方法装饰器时绑定此

Javascript 在React中使用方法装饰器时绑定此,javascript,reactjs,decorator,ecmascript-next,Javascript,Reactjs,Decorator,Ecmascript Next,如何将此与transform decorators legacyBabel插件绑定? 例如,我有一些简单的装饰。装饰器可以工作,但组件的方法中未定义此 fucntion myDecorator(target, name, descriptor) { var oldValue = descriptor.value; descriptor.value = function() { ...// Doing some stuff here I need the deco

如何将
transform decorators legacy
Babel插件绑定? 例如,我有一些简单的装饰。装饰器可以工作,但组件的方法中未定义此

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与一些decorator一起使用,我会得到
TypeError:属性描述符无效。不能同时指定访问器和值或可写属性,因为

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

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


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

这不是
.bind
ing修饰方法的问题

但有些东西你错过了。即使您已将
.bind
您的
myMethod
内部的
构造函数
绑定到类,但无论从何处调用它,
myDecorator
都会修改执行范围

oldValue.apply(null,参数)

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

所以你想要的是:

oldValue.apply(这个,参数)


看这把小提琴:

这就是我解决这个问题的方法: 使用上述decorator中的代码:

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)
            };
        }
    };
}

按照您的建议执行,
这个
指向的是
React.Component
,而不是
MyClass
Hmm,似乎有效。有趣的是,我100%确定我尝试过同样的方法,但它不起作用,
这个
未定义的
。请您解释一下为什么需要行
props=this.props
?我认为这没有必要,您可以这样做:
var oldValue=descriptor.value;descriptor.value=function(){return oldValue.apply(this,arguments);}返回描述符检查我答案中的提琴。这是因为您在示例的构造函数中第一次绑定到
This
。这不适用于需要参数的装饰器。