5

@myDecorator我对使用语法(使用 babel)的能力感到非常兴奋。我正在尝试装饰其中一个生命周期功能,具体来说componentWillMount,并检查装饰器中组件的propsand context。但是,我似乎无法访问propscontext。我不确定这是否是一种反模式,或者我是否只是在解决这个问题。

小例子:

// TestComponent.jsx
import checkProps from 'checkProps.js';

class TestComponent extends React.Component {
    @checkProps
    componentWillMount() {
        // Do something.
    }

    render() {
       return <div>My Component</div>
    } 
}

// checkProps.js
export function checkProps(target) {
    console.log(target.props);
}

我也尝试过装饰器和检查的箭头函数this,但我不认为装饰器组合的东西是这样工作的。

我还尝试将我的装饰器设为工厂并传入,this.propsthis.contextthis装饰组件生命周期函数时未定义。

4

1 回答 1

11

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 阶段,我们越来越接近

于 2016-03-29T14:28:45.620 回答