2015-08-21 40 views
9

有什麼方法可以在React ES6類組件中包含mixin嗎? (即extends React.Component)?如果是這樣,那麼官方的做法是什麼?ESR React組件中的PureRenderMixin

我想在包含PureRenderMixin的組件中包含一個不可變狀態的組件,以加速差異化進程。

回答

12

通常有兩種解決方案,混入在ES6風格的陣營類:

  1. 創建一個高階組件(例如here
  2. 使用一個裝飾,如果你」願意啓用Babel早期階段的ES7提案(例如here

我實際上並沒有實現trie d我爲#2鏈接的圖書館,但裝飾者罷工我作爲一個優雅的替代mixin。

+0

我很感謝您爲我做這項研究:) –

0

我使用react-mixin如果我想在我的es6反應組件中有mixin,但我沒有嘗試使用PureRenderMixin這個庫。

14

https://facebook.github.io/react/docs/shallow-compare.html

shallowCompare是同時使用具有陣營ES6類的輔助功能以實現相同 功能PureRenderMixin。

import shallowCompare from 'react-addons-shallow-compare'; 

export default class SampleComponent extends React.Component { 

    shouldComponentUpdate(nextProps, nextState) { 
    // pure render 
    return shallowCompare(this, nextProps, nextState); 
    } 

    render() { 
    return <div className={this.props.className}>foo</div>; 
    } 
} 

PureRenderMixinSource code是:

var ReactComponentWithPureRenderMixin = { 
    shouldComponentUpdate: function(nextProps, nextState) { 
    return shallowCompare(this, nextProps, nextState); 
    }, 
}; 

所以,當你使用PureRenderMixin,你實際使用shallowCompare

UPDATE 15.3.0

添加React.PureComponent - 擴展的新基類,現在替換react-addons-pure-render-mixin mixin不適用於ES2015類。

+0

自從您__can__將'PureRenderMixin'與'es6'一起使用,究竟是什麼差異? – Tjorriemorrie

+0

@Tjorriemorrie,如果您在構造函數中討論類似'this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);'的代碼,而不是使用'shallowCompare' addone的另一種方式。 請參閱https://github.com/facebook/react/blob/v15.0.0/src/addons/ReactComponentWithPureRenderMixin.js#L41-L43 –