装饰器与React组件中的方法

时间:2018-10-11 17:29:52

标签: javascript reactjs ecmascript-6 babeljs decorator

我正在尝试在我的react组件中装饰一种方法,并检查道具和状态,然后对它们进行一些处理。但是,我不确定为什么this始终是undefined,但是当我使用上述生命周期方法时却得到class / this上下文。

示例代码:

import dosomething from 'utils/dosomething';
import Button from 'button';
class App extends React.Component {
  // this shows this context in dosomething
  @dosomething
  componentWillMount() {
      // John Doe written codes.
  }
  // this doesn't shows this context in dosomething
  @dosomething
  someMethod() {
      // John Doe written codes.
  }
  render() {
      return <Button
                {...this.props}
                onClick={this.someMethod}
              />
  }
}

然后是我的装饰器

//utils/dosomething.js 
export function dosomething(target, name, descriptor) {
  const decoratee = descriptor.value;
  descriptor.value = function decorated(...args) {
    // shows defined for componentWillMount but undefined for methods
    console.log(this);
    decoratee.apply(this, args);
  };
}

如何从方法访问this上下文?

0 个答案:

没有答案