# 2-7_畫面組裝的藍圖:component 初探 --- ## 2-7-1_什麼是 component - 由開發者自己定義的畫面元件藍圖,負責裝載特定範圍的畫面或邏輯 - 根據需求抽象化設計出 component,就能將複雜的畫面拆解成可以重複使用的積木零件 --- - 抽象化 - 根據需求將關心的特徵與行為歸納出來,設計出適用於特定情境和意義範圍的流程或邏輯,並將實作細節或複雜性封裝在內部以便重新使用 --- ## 2-7-2_定義 component - 可以用普通的 JavaScript 函式來定義 - 接收 props(properties) 資料作為參數,並回傳 1 個 React element 作為畫面的結構 --- - 【注意】:命名的首字母必須為大寫 ```jsx! export default function CustomButton(props) { return ( <button type="button">I'm a button</button> ) } ``` ## 2-7-3_呼叫 component ```jsx! <CustomButton /> ``` --- ### 【藍圖與實例】 - component function 本身是描述特徵、流程與行為的藍圖 - 呼叫 component 則是會產生實際的實例 - 同份藍圖所產生的實例是獨立存在的,彼此之間不會互相影響 --- ## 2-7-4_import 與 export component - export ```jsx= export default function CustomButton(props) { return ( <button type="button">I'm a button</button> ) } ``` ```jsx= function CustomButton(props) { return ( <button type="button">I'm a button</button> ) } export default CustomButton ``` --- - import ```jsx= import CustomButton from '...' ``` --- ### 【從同份檔案 export 與 import 多個 component】 - 使用 `name export` ```jsx= export function ComponentA() { ... } export function ComponentB() { ... } ``` ```jsx= import { ComponentA, ComponentB } from '..' ``` --- - 每個檔案最多可以有幾個 `default export`? - A. 1 個 - B. 2 個 - C. 3 個 --- ## 2-7-5_props ### 【什麼是 props】 - 將特定的參數從外部傳遞給 component ,可以用來產生流程的客製化,應付更多的需求 --- ### 【呼叫 component 時傳入 props】 ```jsx! <Card title="" content="" /> ``` ### 【接收與使用 props】 ```jsx! export default function Card(props) { return ( <h3>{props.title}</h3> <p>{props.content}</p> ) } ``` --- - React 沒有限制資料型別,props 可以是 - 基本型別 - 物件、陣列、函式 - React element --- ### 【props 是唯獨且不可被修改的】 - 為了維護單向資料流的可靠性 - 保證資料的源頭是唯一、不變、可追蹤的 --- - 錯誤案例 ```jsx! props.price = props.price * 0.9 ``` - 正確範例:把修改後的數值指派給新建立的變數 ```jsx! const discountPrice = props.price * 0.9 ``` --- ### 【修改 props 但無法被 React 偵測到的危害案例】 > <https://codesandbox.io/s/jd8k64> --- ### 【特殊的 props:children】 - 畫面容器型 ```jsx! function Card(props) { return ( <div className="card"> {props.children} </div> ) } ``` ```jsx! function App() { return ( <Card> <h3>Title</h3> <p>Content</p> </Card> ) } ``` --- ## 2-7-7_component 的 render 與 re-render --- ### 【component 的一次 render】 - 當我們將 component 以 React element 的形式呼叫時,React 在繪製畫面時就會執行 component 1 次 --- ### 【從一律重繪策略到 component 的 re-render】 - 當 component 內部的狀態資料發生改變時,React 再次執行 component function 來產生對應的新版資料的新版畫面 --- ## 2-7-8_為什麼 component 命名中的首字母必須為大寫 - 開發慣例:讓開發者好分辨 - transpiler 在做 JSX 轉譯的時候,會依照大小寫來判斷 - 小寫:根據對應的 DOM 標籤名稱 - 大寫:判斷為 component function --- - 關於 Git 的檔案名稱大小寫問題與修正 > <https://israynotarray.com/git/20221230/27133639/> --- ## Review --- ### 什麼是 component --- ### 什麼是抽象化 --- ### 什麼是 props?為何是唯讀的? --- ### 什麼是 component 的 render、re-render? --- ### 為什麼 component 命名的首個字母要大寫 ---
{"title":"2-7_畫面組裝的藍圖:component 初探","description":"","contributors":"[{\"id\":\"24187e66-a778-4778-a2dc-98f9cdf79fe0\",\"add\":2904,\"del\":1}]","showTags":"true","image":"https://hackmd.io/_uploads/HJND8L4R6.jpg"}
    221 views