2017-10-09 74 views
0

我有一個呈現多個子組件的父組件。每個子組件都應該在每個窗口大小調整事件中重新呈現自己。將事件偵聽器添加到多個子組件或簡單父組件

我想知道,如果它是更好地作出反應的做法是:

  1. 在每個子組件附加事件聽衆componentDidMount,因爲它是子組件的責任來聽此事件。
  2. 將單個事件偵聽器附加到父組件的componentDidMount,並強制其子組件在該事件觸發時重新呈現。

從性能的觀點來看,我認爲#2更好,但從React-methodology的觀點來看,我認爲#1更好。思考?

+0

聽起來類似於反應文檔提升狀態的例子。 https://reactjs.org/docs/lifting-state-up.html – spirift

回答

1

反應的默認行爲是每次更改其狀態或道具時重新呈現組件(及其子組件)。

this.setState({isResized: true}); //trigger the rendering 

你不必來處理每一個孩子裏面調整大小,只需辦理窗口大小調整(可能與適當的去抖,以提高性能)在父組件,因此設定的狀態,孩子們會無需任何其他代碼即可重新渲染。

這樣的事情應該工作

class ParentComponent extends Component{ 

resizeCallback(e){ 
    this.setState({'isResized', true}); //re-render even MyChildComponent 
} 
componentDidMount(){ 
    window.addEventListener('resize', this.resizeCallback); 
    //alternatively with underscorejs debounce 
    //window.addEventListener("resize", _.debounce(this.resizeCallback, 300)); 
} 
componentWillUnmount(){ 
    window.removeEventListener('resize', this.resizeCallback); 
} 
render(){ 
    <div> 
    <MyChildComponent/> 
    </div> 
} 
} 
相關問題