React 組件之間的通訊方式

在項目開發的過程當中,隨着應用功能複雜度的增長和組件層次劃分的需求,組件之間的通訊愈來愈多,
我大體認爲組件之間的通訊分爲3種:父-子組件通訊、子-父組件通訊和同級組件之間的通訊。app

  • 1.父-子組件通訊函數

  • 2.子-父組件通訊this

  • 3.同級組件之間的通訊spa

1.父-子組件通訊

1.1通訊的手段

這是最多見的通訊方式,父組件只須要將子組件須要的props傳給子組件,子組件直接經過this.props來使用。設計

1.2 通訊內容

更多要提的是如何合理的設置子組件的props,要想將子組件設計成一個複用性強的通用組件,須要將可以複用的部分抽象出來,
抽象出來的props有兩種造成,一種是簡單的變量,另外一種是抽象出來處理某種邏輯的函數。code

以Header 組件爲例
image descriptionorm

抽象出來三個props,分別是中間的title,渲染組件左邊的renderLeftComponent,渲染組件右邊的renderRightComponent
Header的 部分實現事件

renderLeftComponent () {
    let leftDOM = {};
 
    if(this.props.renderLeftComponent) {
        return this.props.renderLeftComponent();
    }
    if (this.props.showBack) {
        let backFunc = this.props.onBack || this.goBack;
        leftDOM = (<a onClick={backFunc.bind(this)}><i className="icon left-icon icon-left-arrow"></i></a>);
    }
    return leftDOM;
}
renderRightComponent () {
    if(this.props.renderRightComponent) {
    return this.props.renderRightComponent();
}
}
render () {
    return (
        <header className="header-wrapper">
            <div className="header header-normal">
            {this.renderLeftComponent()}
            <span>{this.props.title || '維C果蔬'}</span>
            {this.renderRightComponent()}
            </div>
        </header>
    );
}

1.3 通訊的動機

1.1中Header組件 props的通訊動機 是子組件須要這樣的屬性來完成本身的展現。還有一種動機能夠統稱向子組件傳遞監聽事件,
前一種是子組件的需求,後一種更多的是父組件的需求,例如Listview的onEndReached這種屬性,觸發源是在子組件中,當子組件
的事件被觸發或者達到某種狀態的時候,調用父組件從屬性中傳過來的方法。ip

2.子-父組件通訊

2.1 通訊的手段

父-子組件通訊的手段是經過子組件的props是子組件用父組件的東西,子-父組件通訊,是父組件用子組件的東西,應該將傳遞的內容直接寫在子組件上,而後給子組件設置ref,父組件直接經過ref操做子組件的屬性。開發

2.2 通訊的內容

子組件的屬性

2.3 通訊的動機

父組件想要調用子組件的屬性

3.同級組件之間的通訊

同級組件之間的通訊,是構建複雜界面的粘合劑,哎呦喂,我好會比喻啊
以維C果蔬的首頁爲例:
image description

通訊1: Listview須要offsetHeight屬性,Listview

Height的計算公式:window.innerHeight-Banner的Height-Menu的Height,

而Banner和Menu的Height都是須要在其Mount的時候才能計算。

通訊2: ListView須要Menu的MenuId,纔可以根據MenuId獲取sku數據。

3.1通訊的方式

同級組件之間的通訊仍是須要經過父組件做爲中介,利用屢次父-子組件通訊,項目中將須要傳遞的數據放在了父組件的state中,變更時能夠自動的同步傳遞。
將 bannerHeight,menuHeight,MenuId放在state中。
父組件代碼示意:

this.state {
    bannerHeight: 0,
    menuHeight: 0,
    MenuId: 0
}
setBannerHeight(height) {
    this.setState({bannerHeight:height});
}
setMenuHeight(height) {
    this.setState({menuHeight:height});
}
onMenuClick(menuId) {
    this.setState({menuId:menuId});
}
<Banner setBannerHeight={this.setBannerHeight.bind(this)} />
<Menu setMenuHeight={the.setMenuHeight.bind(this)} onMenuClick={this.onMenuClick.bind(this)} />
<SkuList offsetHeight={this.state.bannerHeight + this.state.menuHeight} menuId={this.state.menuId} />

3.2通訊的動機

當組件須要的props,不能直接從父組件中獲取時,須要父組件做爲中介,再與其餘的組件進行通訊獲取。

相關文章
相關標籤/搜索