修饰react组件以添加生命周期方法
Decorate react component to add lifecycle methods
我正在尝试创建一个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 .
相关文章:
- 组件生命周期问题/无法处理未定义的问题
- 渲染方法与生命周期方法中的React计算
- 注册后是否可以定义HTML5自定义元素中的生命周期回调
- 管理动态磁贴和应用程序生命周期
- 主干网的生命周期.js创建过程中的视图
- 使用Ember中的组件生命周期事件
- 关于Angular 1.5零部件生命周期挂钩
- 更新数据时的React.js生命周期
- 雷杜克斯.从容器组件描述表示组件的生命周期方法
- 增加服务工作线程的生命周期
- 是否有一种自动方法来确定(或查找)库的生命周期结束/支持终止通知
- 如何将请求生命周期事件封装在 happy.js 中
- 使用 Async.parallel 我的参数的生命周期不会超过使用 MongoDB 的 NodeJS 中的异步调用
- 聚合物元素注册和生命周期(创建和准备调用两次)
- E_UNKNOWN beforeCreate 和其他生命周期回调的响应错误
- Aurelia 组件生命周期中的远程服务
- 节点.js简单的 Web 服务器请求生命周期
- 角度引导程序生命周期:在完全加载后运行代码
- 主干提取集合生命周期,从响应设置属性
- JQuery 插件架构,用于定义对象和变量生命周期