ES7 ECMAScript 装饰器具有相同的 API,Object.defineProperty(target, name, descriptor)
因此target
参数是应用装饰器时的类,而不是调用时的类React
。要影响装饰器在运行时所做的事情,您必须修改descriptor.value
被装饰的实际函数:
export function checkProps(target, name, descriptor) {
// Save the original method, it'd be a good idea
// to check that it really is a function
const decoratee = descriptor.value;
// Modify the descriptor to return our decorator
// function instead of the original
descriptor.value = function decorated(...args) {
// Do something before ...
console.log('before: ' + name, this.props, args);
// Calling the decorated method on this object
// with some arguments that could have been
// augmented by this decorator
decoratee.apply(this, args);
// Do something after ...
console.log('after: ' + name);
};
}
// Or if you wanted to use a factory function to supply some configuration
// to the decorator you can do it this way
export function checkProps(config) {
return function configurableCheckProps(target, name, descriptor) {
// Save the original method, it'd be a good idea
// to check that it really is a function
const decoratee = descriptor.value;
if (config.someOption) {
// Do something based on the config
}
// Modify the descriptor to return our decorator
// function instead of the original
descriptor.value = function decorated(...args) {
// Do something before ...
console.log('before: ' + name, this.props, args);
if (config.someOption) {
// Do something based on the config
}
// Calling the decorated method on this object
// with some arguments that could have been
// augmented by this decorator
decoratee.apply(this, args);
// Do something after ...
console.log('after: ' + name);
};
};
}
这是一个示例,它还修改了更彻底地演示这一点的方法的行为。
希望这可以帮助。快乐编码!
编辑:正如评论者指出的那样,装饰器不是 ES7 的一部分,但截至 2016 年 3 月,该提案仍处于 Stage 1,我的错
EDIT2:截至 2018 年 6 月,提案仍在提案中,仍处于第 2 阶段,我们越来越接近