Javascript 装饰react组件以添加生命周期方法
我正在尝试创建一个decorator方法,它将把一些默认的生命周期方法添加到react组件中。我的目标是向组件中添加一些默认功能,例如,所有组件都应该能够在Javascript 装饰react组件以添加生命周期方法,javascript,reactjs,decorator,Javascript,Reactjs,Decorator,我正在尝试创建一个decorator方法,它将把一些默认的生命周期方法添加到react组件中。我的目标是向组件中添加一些默认功能,例如,所有组件都应该能够在组件willmount上执行特定的操作 我读了几篇文章,发现了这个。它可用于向反应组分添加新道具 export default function context(contextTypes, context) { return function (DecoratedComponent) { return class {
组件willmount
上执行特定的操作
我读了几篇文章,发现了这个。它可用于向反应组分添加新道具
export default function context(contextTypes, context) {
return function (DecoratedComponent) {
return class {
static childContextTypes = contextTypes;
getChildContext() {
return context;
}
render() {
return (
<DecoratedComponent {...this.props} />
);
}
}
}
}
对正确的方向有什么想法吗
参考文献:
如果您正在使用Babel和stage 1或stage 0预设,您可以使用以下方法: 首先,定义您的装饰功能,例如:
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>
);
}
};
@lifecycleDefaults
导出类页面扩展了React.Component{
render(){
返回(
装饰师们好!
);
}
};
组件“Page”现在有componentWillMount、componentDidMount和componentWillUnmount方法。它们在组件生命周期的预期时间运行
2个注意事项:1)我正在使用babel transform decorators遗留插件;2) 我正在使用Webpack构建我的项目,包括babel的transform运行时。YMMV
@lifecycleDefaults
export class Page extends React.Component {
render() {
return (
<div>Hello decorators!</div>
);
}
};