React 組件之間的通信方式


在項目開發的過程中,隨着應用功能復雜度的增加和組件層次划分的需求,組件之間的通信越來越多,

我大致認為組件之間的通信分為3種:父-子組件通信、子-父組件通信和同級組件之間的通信。

1.父-子組件通信

1.1通信的手段

這是最常見的通信方式,父組件只需要將子組件需要的props傳給子組件,子組件直接通過this.props來使用。

1.2 通信內容

更多要提的是如何合理的設置子組件的props,要想將子組件設計成一個復用性強的通用組件,需要將能夠復用的部分抽象出來,

抽象出來的props有兩種形成,一種是簡單的變量,另一種是抽象出來處理某種邏輯的函數。

以Header 組件為例      

 

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

Header的 部分實現

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

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 || '美團商超'}</span>

            {this.renderRightComponent()}

            </div>

        </header>

    );

}

 

1.3 通信的動機

1.1中Header組件 props的通信動機 是子組件需要這樣的屬性來完成自己的展示。還有一種動機可以統稱向子組件傳遞監聽事件,

前一種是子組件的需求,后一種更多的是父組件的需求,例如Listview的onEndReached這種屬性,觸發源是在子組件中,當子組件

的事件被觸發或者達到某種狀態的時候,調用父組件從屬性中傳過來的方法。

 

2. 子-父組件通信

2.1 通信的手段

父-子組件通信的手段是通過子組件的props是子組件用父組件的東西,子-父組件通信,是父組件用子組件的東西,腫么用,在開發過程中

暫時沒有用到這種情景。我想到的方法就是將傳遞的內容直接寫在子組件上,然后給子組件設置ref,父組件直接通過ref操作子組件的屬性。

2.2 通信的內容

子組件的屬性

2.3 通信的動機

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

 

3 同級組件之間的通信

同級組件之間的通信,是構建復雜界面的粘合劑,哎呦喂,我好會比喻啊

以生鮮的首頁為例:

 

通信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中。

父組件代碼示意:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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,不能直接從父組件中獲取時,需要父組件作為中介,再與其他的組件進行通信獲取。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM