我正在尝试在我的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
上下文?