【问题标题】:Shared componentDidMount() function共享 componentDidMount() 函数
【发布时间】:2015-10-12 14:37:38
【问题描述】:

我有几个函数具有完全相同的 componentDidMount 函数。

有办法分享吗?

我正在使用 ES6,显然没有办法使用 Mixin。

感谢您的帮助

【问题讨论】:

    标签: javascript reactjs composition


    【解决方案1】:

    这适合你吗?

    class Parent extends React.Component {
      constructor(props) {
        super(props);
      }
    
      componentDidMount() {
        ...
      }
    }
    
    class Child extends Parent {
      constructor(props) {
        super(props);
      }
    }
    

    【讨论】:

    • 是的,但我宁愿使用组合而不是 inerithance
    【解决方案2】:

    最后我创建了一个文件 animationCompose.js

    const composeAnimation = {
        componentDidMount(){
            // Get the components DOM node
            var elem = React.findDOMNode(this);
            // Set the opacity of the element to 0
            elem.style.opacity = 0;
            window.requestAnimationFrame(function() {
                // Now set a transition on the opacity
                elem.style.transition = "opacity 250ms";
                // and set the opacity to 1
                elem.style.opacity = 1;
            });
        }
    }
    
    
    export default composeAnimation;
    

    然后在我的 Component.js 中使用 es7 装饰器

    import mixin from 'mixim-decorator'
    import composeAnimation from '../decorators/composeAnimation'
    
    @mixin(composeAnimation)
    class Component extends React.Component {
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2012-05-14
      • 2018-08-23
      • 2017-10-08
      相关资源
      最近更新 更多