2015-10-15 83 views
2

我想创建一个装饰器方法,它会将一些默认生命周期方法添加到反应组件中。我的目标是在组件中添加一些默认功能,例如所有组件都应该能够在componentWillMount上执行特定的事情。装饰反应组件添加生命周期方法

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

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

+0

https://medium.com/@gigobyte/enhancing-react-components-with-decorators-441320e8606a – zloctb

回答

2

如果您使用巴贝尔与1级或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> 
     ); 
    } 
}; 

组件'页面'现在具有方法componentWillMount,componentDidMount和componentWillUnmount。它们在组件生命周期的预期时间运行。 1)我使用的是babel transform-decorators-legacy插件; 2)我正在使用Webpack构建我的项目,并附带了babel的转换运行时。因人而异。