2016-11-28 15 views
1

如何綁定thistransform-decorators-legacy Babel插件? 例如,我有一些簡單的裝飾器。裝飾工程,但this未定義組件的方法。在React中使用方法裝飾器時將此屬性綁定到

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

如果我嘗試了一些@autobind裝飾用@myDecorator我得到 TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute,因爲

的數據描述符是具有價值,這可能會或可能是不可寫的屬性。訪問器描述符是由getter-setter函數對描述的屬性。描述符必須是這兩種口味之一;它不可能是兩個。

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

綁定在構造函數(this.myMethod = thid.myMethod.bind(this))似乎也沒有幫助,因爲你綁定undecorated方法。

回答

1

這難道不是與.bind ING裝飾方法的問題。

但是有一些你錯過了。即使你做了你的.bindmyMethod裏面constructor的類,當你調用它,不管來自哪裏,myDecorator修改執行範圍。

oldValue.apply(null, arguments)

基本上,與null替換目標範圍(MyClass)。

所以,你要的是這樣的:

oldValue.apply(this, arguments)

看到這個小提琴:http://jsfiddle.net/free_soul/0n6v1dtp/

+0

按照你的建議,'this'指向'React.Component'而不是'MyCl屁股' – OlehZiniak

+0

嗯,似乎工作。有趣的是,我100%肯定我已經嘗試過相同的方法,並且它不工作,'this'是'undefined'。你能解釋一下爲什麼你需要'props = this.props'這一行嗎? – OlehZiniak

0

這是我設法解決這個問題: 從提到@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) 
      }; 
     } 
    }; 
} 
+0

我不認爲這是必要的,而是你可以這樣做:'var oldValue = descriptor.value; descriptor.value = function(){return oldValue.apply(this,arguments); }返回描述符;'檢查我的答案中的小提琴。 –

+0

這是因爲你的第一個綁定到你的例子的構造函數中的'this'。這對於需要參數的修飾器不起作用。 –

相關問題