簡體   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