修饰react组件以添加生命周期方法

Decorate react component to add lifecycle methods

本文关键字:生命 周期 方法 添加 react 组件 修饰      更新时间:2023-09-26

我正在尝试创建一个decorator方法,它将添加一些默认的生命周期方法到react组件中。我的目标是在组件中添加一些默认功能,例如所有组件都应该能够在componentWillMount上执行特定的操作。

我读了几篇文章,发现了这个。它可以用来为react组件添加新的道具。

export default function context(contextTypes, context) {
    return function (DecoratedComponent) {
        return class {
            static childContextTypes = contextTypes;
            getChildContext() {
              return context;
            }
            render() {
              return (
                <DecoratedComponent {...this.props} />
              );
            }
        }
    }
}

但我不确定如何添加类方法,如componentWillMount。我能不能写点

Object.assign(DecoratedComponent.prototype, {
    componentWillMount: () => {
        // do something
    }
})

有什么正确的方向吗?

:

http://asaf.github.io/blog/2015/06/23/extending-behavior-of-react-components-by-es6-decorators/https://gist.github.com/motiz88/3db323f018975efce575

如果您正在使用Babel与阶段1或阶段0预设,您可以使用以下方法:

首先,定义你的decorator函数,例如:
function lifecycleDefaults(target) {
    target.prototype.componentWillMount = function() {
        console.log('componentWillMount ran from decorator!');
        console.log('this.props is still accessible', this.props);
    }
    target.prototype.componentWillUnmount = function() {
        console.log('componentWillUnmount ran from decorator!');
        console.log('this.props is still accessible', this.props);
    }
    target.prototype.componentDidMount = function() {
        console.log('componentDidMount ran from decorator!');
        console.log('this.props is still accessible', this.props);
    }
}

之后,使用你刚刚定义的函数修饰一个组件,例如:

@lifecycleDefaults
export class Page extends React.Component {
    render() {
        return (
            <div>Hello decorators!</div>
        );
    }
};

组件'Page'现在有了componentWillMount, componentDidMount和componentWillUnmount方法。它们在组件生命周期中的预期时间运行。

2个警告:1)我使用babel transformer -decorators-legacy插件;2)我正在使用Webpack构建我的项目,其中包括babel的转换运行时。YMMV .