元件可重複使用性和彼此嵌套。
情境: 但當嵌套越來越多的元件時
=> 將元件拆分至不同檔案。
=> 讓檔案易於閱讀、並可在更多地方重複使用。


You will learn
What a root component file is
How to import and export a component
When to use default and named imports and exports
How to import and export multiple components from one file
How to split components into multiple files


Q1: React 中的根元件 (Root Component) 是什麼?

The root component file

根元件位在哪 根據專案如何創建
  • 這些元件目前位於根元件檔案中,命名為 App.js。
  • 在 Create React App 中,App 位於 src/App.js 。
  • 根據設置setup,若使用基於檔案的路由框架(例如 Next.js),那麼每個頁面的根元件將不同。

Q2: 如何在檔案輸出 / 引入元件?

Exporting and importing a component

元件拆分至新的檔案 3 steps:
  1. 建立一個新的 JS 檔案,將元件放入。
  2. 從新檔案中輸出函式元件(使用default / 命名輸出)。
  3. 在使用該元件的檔案中引入 元件(使用對應的技巧 引入default輸出 / 命名輸出)。
    ### 補 圖示

DEEP DIVE

Default vs Named export

  • 同個檔案內,可使用1種或2種export。
  • 一個檔案內,只能有1個 default export,
    但可以有多個named export。

使用情境:

  • 當檔案只有1 個元件時,通常使用 default export。
  • 若要輸出多個元件和values,使用 named export。
  • 元件命名要有意義。
  • 注意: 若沒有命名元件,使用default export,會很難debug。

Q3. 在同一個 JS 檔中,如何定義多個 Component?

在同一個 JS 檔中,如何輸出、引入多個 Component?

Q: 延續上面範例,若只想顯示 Profile元件,而非 Gallery 元件,該如何做?

=> 輸出 Profile元件
但Gallery檔 已經有default export,又不能有2個default export。

=> 可以新增一個檔案,包含default export
or
=> 為 Profile元件加上 named export

NOTE - 使用上偏好

!! 減少混淆 使用default & named export

  • 有些團隊,只使用一種風格(default or named)
  • 或避免在一個檔案中,混合使用2種export

=> 為 Profile元件加上 named export
3steps-move-c

2-c-files.png

default-named-syntax.png

show-1c.png

show-2c.png


#export-import-component #default exports #named exports #named imports







Related Posts

Docker 筆記

Docker 筆記

初探 Fetch

初探 Fetch

ClearDB id 連續遞增問題

ClearDB id 連續遞增問題


Comments