Skip to main content

React中的資料傳遞

一、父傳子(Props 傳遞)

這是最基本的資料傳遞方式:父元件透過 props 將資料傳給子元件。

範例:

// 子元件
function Child({ message }) {
return <p>{message}</p>;
}

// 父元件
function Parent() {
return <Child message="Hello from Parent!" />;
}

export default Parent;

解說:

  • 父元件 Parent 使用 <Child message="..." /> 將資料傳入。

  • 子元件 Child 透過 props.message 取得並顯示。

這樣的資料流 只能單向(由父到子),符合 React 的「單向資料流」設計理念。


二、子傳父(透過回呼函式)

子元件要把資料「回傳」給父元件,常見作法是父元件先定義一個函式,再透過 props 傳給子元件,由子元件呼叫該函式,把資料送回去。

範例:

// 子元件
function Child({ onSend }) {
const handleClick = () => {
onSend("Hello from Child!");
};

return <button onClick={handleClick}>送資料給父元件</button>;
}

// 父元件
function Parent() {
const handleReceive = (data) => {
console.log("父元件收到:", data);
};

return <Child onSend={handleReceive} />;
}

export default Parent;

解說:

  • 父元件 Parent 定義 handleReceive

  • 子元件 Child 按下按鈕後呼叫 onSend("Hello from Child!")

  • 父元件成功收到子元件傳回來的資料。


三、跨層傳遞(Prop Drilling)

當元件層級很深時,資料必須一層一層傳遞下去,這就是「prop drilling」。
但這樣會讓程式碼變得繁瑣,因此通常會搭配 Context API 來解決。

使用 Context API 範例:

import { createContext, useContext } from "react";

// 建立 Context
const UserContext = createContext();

// 最底層子元件
function GrandChild() {
const user = useContext(UserContext);
return <p>使用者名稱:{user.name}</p>;
}

// 中間層元件
function Child() {
return <GrandChild />;
}

// 父元件
function Parent() {
const user = { name: "Aria" };

return (
<UserContext.Provider value={user}>
<Child />
</UserContext.Provider>
);
}

export default Parent;

解說:

  • Parent 透過 UserContext.Provider 提供 user 資料。

  • GrandChild 不需要經過 Child 傳遞,直接用 useContext(UserContext) 就能取得資料。


四、全域狀態管理(Redux、Zustand、Jotai…)

如果資料要被多個不相干的元件共享,使用 Context 雖然可以,但會隨專案變大而難以維護。
這時候就需要 狀態管理工具(例如 Redux、Zustand、Recoil)。

Zustand 為例:

import create from "zustand";

// 建立 store
const useUserStore = create((set) => ({
name: "Aria",
setName: (newName) => set({ name: newName }),
}));

// 顯示名稱
function ShowName() {
const name = useUserStore((state) => state.name);
return <p>使用者名稱:{name}</p>;
}

// 修改名稱
function ChangeName() {
const setName = useUserStore((state) => state.setName);
return <button onClick={() => setName("Musk")}>改成 Musk</button>;
}

// App
function App() {
return (
<>
<ShowName />
<ChangeName />
</>
);
}

export default App;

解說:

  • useUserStore 負責管理狀態。

  • ShowNameChangeName 兩個元件可以共享同一份資料,互相影響。


總結

React 的資料傳遞有不同層次的策略:

  1. 父傳子:props

  2. 子傳父: 用回呼函式。

  3. 跨層傳遞: 用 Context API。

  4. 全域共享: 用狀態管理工具(Redux、Zustand 等)。