props 是「父元件 → 子元件」傳遞資料的機制。
它是唯讀的(read-only),子元件不能直接修改它。
透過 props,可以讓元件更具重用性與彈性。
function MyComponent(props) {
props.c(); // 呼叫父元件傳入的函式
return (
<>
<div>{props.a}</div>
<div>{props.b}</div>
</>
);
}
function App() {
return (
<MyComponent
a="hello world"
b="你好"
c={() => { console.log(123); }}
/>
);
}
<App>
傳入三個參數:a
、b
、c
MyComponent
透過 props.a
、props.b
取得文字內容props.c
是一個函式,子元件中可以直接執行它(這裡會在 console 中印出 123
)由於 props 是一個物件,我們可以用解構賦值的方式直接取出屬性。
function MyComponent({ a, b = '王小明', c }) {
c();
return (
<>
<div>{a}</div>
<div>{b}</div>
</>
);
}
function App() {
return (
<MyComponent
a="hello world"
c={() => { console.log(123); }}
/>
);
}
{ a, b, c }
直接從 props 物件中取出對應屬性。props.
前綴,使程式更簡潔。b
,則使用預設值 '王小明'
。如上例所示,解構賦值中可以直接給屬性設預設值。
function MyComponent({ a, b = '王小明', c }) {
...
}
這樣即使父元件沒傳入 b
,程式仍能正常運作並顯示「王小明」。
這是 props 預設值的最簡單寫法(現代 React 中最常用)。
props 不只能傳文字、數字或函式,也能傳「React 組件」。
這是影片最後展示的重點之一。
function SecondComponent() {
return <h1>hello world</h1>;
}
function MyComponent({ children }) {
return <>{children}</>;
}
function App() {
return (
<MyComponent children={<SecondComponent />} />
);
}
SecondComponent
是一個獨立的子組件。<App>
將它作為屬性傳給 <MyComponent>
。MyComponent
透過解構賦值 { children }
取得傳入的組件,並直接渲染出來。學習影片出處:https://youtu.be/aBTiZfShe-4?si=Igb2aKz3sefA97A5