【发布时间】:2016-01-13 23:37:25
【问题描述】:
我正在尝试创建一个装饰器方法,它将一些默认的生命周期方法添加到反应组件中。我的目标是在组件中添加一些默认功能,例如所有组件都应该能够在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
【问题讨论】:
标签: javascript reactjs decorator