因為前一篇提到了Host Component,今天就來看看React Elements!

綱舉目張👀

  • Elements Describe the Tree
  • Top-Down Reconciliation
  • Conclusion
  • Reference

Elements Describe the Tree

在React的世界裡,畫面是一個樹狀的結構,而這樹狀結構就是由React Elements組成。Element是一個物件的,裡頭描述了這個Element是Components或DOM,以及它期望收到的props,例如:

{
  type: 'button',
  props: {
    className: 'button button-blue',
    children: {
      type: 'b',
      props: {
        children: 'OK!'
      }
    }
  }
}

上面的例子是一個DOM Element,type是string,會直接對應到Host Compoent,運行在瀏覽器上的話就是DOM。
轉換成HTML的話就會是:

<button class='button button-blue'>
  <b>
    OK!
  </b>
</button>

而Element的type不只可以是string也可以是function或class,這類型的Element又叫Component Elemet。
例如一個Button的function component就會是:

{
  type: Button,
  props: {
    color: 'blue',
    children: 'OK!'
  }
}

當React遇到Component Elemet時,他會執行function或執行class的render method,然後function或render method會再回傳新的Element。通常Component Element內會是一個比較複雜的組成,可能包含了另一個Component Element或DOM Element。

React Element就只是一個描述UI的object,簡單卻有彈性,一個Element下可以有很多children,然後一直連貫下去直到最尾端的節點。

const DeleteAccount = () => ({
  type: 'div',
  props: {
    children: [{
      type: 'p',
      props: {
        children: 'Are you sure?'
      }
    }, {
      type: DangerButton,
      props: {
        children: 'Yep'
      }
    }, {
      type: Button,
      props: {
        color: 'blue',
        children: 'Cancel'
      }
   }]
});

React裡的View Tree就是這樣組成的,而Element是object的好處就是React可以很容易的對它們做操作或計算。

Top-Down Reconciliation

上面解釋了React會以Elements表示畫面的樹狀結構,那這些Elements實際上在何時真正轉換成DOM呢?

ReactDOM.render({
  type: App,
  props: {
    isCool: true
  }
}, document.getElementById('root'));

ReactDOM執行render的function後,React就會從Root的Element開始執行(call function or call render method),直到最後拿到的是DOM Element。拿到所有DOM Element後React就知道實際上的UI長什麼樣子。而當有setState被執行時,React也會再跑一次這樣的流程,取得更新後的畫面。

Conclusion

React透過Elements去描繪出畫面!

Reference

By the way

如果你看到了這裡,就順便讓我置入行銷一下 Podcast 節目【BitWise 一點智慧】吧!
【BitWise 一點智慧】主要是以輕鬆的角度,跟大家聊聊軟體開發、 設計、學習、以及一些生活分享。

用Apple收聽
用Spotify收聽
用Google收聽
官方網站

#React #react elements







你可能感興趣的文章

Print a list from n times 1 to n times 9

Print a list from n times 1 to n times 9

CH9 turtle 海龜繪圖模組

CH9 turtle 海龜繪圖模組

Blank line in trello card

Blank line in trello card






留言討論