我正在尝试创建一个装饰器方法,它将在 react 组件中添加一些默认的生命周期方法。我的目标是向组件添加一些默认功能,例如所有组件都应该能够在 componentWillMount
上执行特定事情。
我读了几篇文章并发现了这个。它可用于向 React 组件添加新的 props。
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
最佳答案
如果您使用带有 stage 1 或 stage 0 预设的 Babel,则可以使用以下方法:
首先,定义你的装饰器函数,例如:
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 transform-decorators-legacy 插件; 2)我正在使用 Webpack 构建我的项目,其中包含 babel 的转换运行时。 YMMV。
关于javascript - 装饰react组件以添加生命周期方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33149772/