2016-07-26 33 views
-1

對於多個React組件,我想在React的生命週期中注入一個通用代碼。
有什麼好方法嗎?如何在組件中注入通用代碼React

var ComponentA = React.createClass({ 
    componentWillMount: function() { 

    }, 
    componentDidUpdate: function(){ 
     //inject common code 
    },... 

var ComponentB = React.createClass({ 
    componentWillMount: function() { 

    }, 
    componentDidUpdate: function(){ 
     //inject common code 
    },... 

回答

0

雖然通過@jzm建議高階組件的做法是better,你也可以使用混入:

var myMixin = { 
     componentWillMount: function(){ 
     //common code 
     }, 
     componentDidUpdate: function(){ 
     //common code 
     } 
}; 
var ComponentA = React.createClass({ 
    mixin: [myMixin] 
}); 
var ComponentB = React.createClass({ 
    mixin: [myMixin] 
}) 
+0

事實上,它沒有工作的@jzm方法,我也在mixin中解決。 mixin看起來很有用。 – izuchy

+0

對不起,你是什麼意思'我在mixin中也解決了? –

+0

@izuchy將來不會支持Mixins的反應。所以他們不是解決這個問題的正確方法。 https://facebook.github.io/react/blog/2016/07/13/mixins-considered-harmful.html – jzm

1

你是說只是在多個組件間共享函數?如果是這樣,你可以讓他們在一個單獨的文件,並將其導入在任何你需要:

// common js 

function hello() { 
    console.log('hello'); 
} 

module.exports = hello; 

// your component 
var hello = require('./common'); 

var ComponentA = React.createClass({ 
    componentDidUpdate: function(){ 
     hello(); 
    },//... 

http://www.webpackbin.com/Nk80m1x_W


你能做的就是創建一個包裝的另一件事情(高階)組件:

var WrapperComponent = React.createClass({ 
    componentDidUpdate: function() { 
    // code you want to inject. 
    }, 
    render: function() { 
    return(<div>{this.props.children}</div>); 
    } 
}); 

那麼每當你需要使用一個組件與生命週期,您可以在JSX做到這一點:

<WrapperComponent> 
    <ComponentA /> 
</WrapperComponent> 
+0

非常感謝你。但是由於組件的數量很大,我想以某種你知道的方式來考慮,比如覆蓋生命週期? – izuchy

+0

@izuchy查看更新 – jzm

+0

太棒了!謝謝。 – izuchy