具有React组件的装饰器

Sha*_*awn 5 javascript reactjs babeljs ecmascript-next

我对使用@myDecorator语法的能力感到非常兴奋(使用babel).我试图装饰一个生命周期函数,具体来说componentWillMount,检查装饰器中的组件propscontext.但是,我似乎无法访问propscontext.我不确定这是否是一种反模式,或者我是否只是出错了.

小例子:

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

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

    render() {
       return <div>My Component</div>
    } 
}
Run Code Online (Sandbox Code Playgroud)

// checkProps.js
export function checkProps(target) {
    console.log(target.props);
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过装饰器和检查的箭头函数this,但我不认为装饰器会以这种方式组合.

我也尝试让我的装饰器成为工厂并传入this.props,this.contextthis在装饰组件生命周期功能时未定义.

mfe*_*eis 10

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);
        };
    };
} 
Run Code Online (Sandbox Code Playgroud)

这是一个示例,它还修改了一个更彻底地演示此方法的方法的行为.

希望这可以帮助.快乐的编码!

编辑:正如一位评论者指出,装饰者不是ES7的一部分,但截至2016年3月,提案仍处于第一阶段,我的不好

EDIT2:截至2018年6月,提案仍在第2阶段,我们越来越近了