? React 最常用 props 用法 10 例
? 1. 傳遞字符串 / 數字 / 布爾值
function UserCard({ name, age, isVip }) {return (<div>{name} - {age} - {isVip ? 'VIP' : '普通用戶'}</div>);
}<UserCard name="張三" age={18} isVip={true} />
? 2. 傳遞函數(事件)
function Button({ onClick }) {return <button onClick={onClick}>點我</button>;
}<Button onClick={() => alert('你好!')} />
? 3. 傳遞 children(嵌套內容)
function Layout({ children }) {return <div className="layout">{children}</div>;
}<Layout><p>這是頁面內容</p>
</Layout>
? 4. 解構 props
function Welcome({ name }) {return <h1>歡迎 {name}</h1>;
}
? 5. 設置默認值
function Title({ text = "默認標題" }) {return <h2>{text}</h2>;
}<Title /> // 顯示“默認標題”
? 6. 傳遞數組 / 對象
function List({ items }) {return <ul>{items.map(item => <li key={item}>{item}</li>)}</ul>;
}<List items={['蘋果', '香蕉']} />
? 7. props 展開傳遞(...props)
function Input(props) {return <input {...props} />;
}<Input type="text" placeholder="請輸入..." />
? 8. props 類型校驗(開發時用)
import PropTypes from 'prop-types';function User({ name }) {return <div>{name}</div>;
}User.propTypes = {name: PropTypes.string.isRequired,
};
? 9. 使用函數+參數(如事件傳參)
function Item({ id, onDelete }) {return <button onClick={() => onDelete(id)}>刪除</button>;
}<Item id={1} onDelete={(id) => console.log('刪除', id)} />
? 10. 父傳子 + 子組件回調
function Child({ onLogin }) {return <button onClick={onLogin}>登錄</button>;
}function Parent() {const handleLogin = () => console.log("登錄成功!");return <Child onLogin={handleLogin} />;
}
? 補充:ref 轉發(略高階)
const Input = React.forwardRef((props, ref) => (<input ref={ref} {...props} />
));function App() {const ref = React.useRef();return (<><Input ref={ref} /><button onClick={() => ref.current.focus()}>聚焦</button></>);
}
? 小結:最常見的 props 類型
類型 | 用途 | 示例 |
---|---|---|
string | 展示文字內容 | title="標題" |
number | 計數、評分等 | count={5} |
boolean | 控制顯示/開關 | isOpen={true} |
function | 綁定事件 | onClick={() => {}} |
children | 嵌套組件內容 | <Comp>內容</Comp> |
array | 列表/選項 | items={[1, 2, 3]} |
object | 配置項、用戶信息等 | user={{ name: '張三' }} |
...props | 展開傳遞給 HTML 元素 | <button {...props}>按鈕</button> |
useContext
—— 它是 React 中用于跨組件傳遞數據的一個非常重要的方式,屬于“替代 props 多層傳遞”的方案。
useContext
和 props 的關系、區別、使用場景與完整例子,并結合 props 的理解一并講清楚。
? React 中 useContext
與 props 的配合與區別
🔍 一句話理解
props:父 → 子逐層傳遞,顯式、靈活但繁瑣。
context + useContext:全局/跨層傳遞,適合狀態共享,如主題、語言、用戶登錄信息等。
? 1. useContext 基本使用步驟
🔧 第一步:創建 Context
import { createContext } from "react";const UserContext = createContext(null);
🔧 第二步:提供 Provider,在頂層注入值
function App() {return (<UserContext.Provider value={{ name: "張三", isVip: true }}><Page /></UserContext.Provider>);
}
🔧 第三步:在任意子組件中使用 useContext 獲取值
import { useContext } from "react";function Page() {const user = useContext(UserContext);return <div>你好,{user.name},VIP:{user.isVip ? "是" : "否"}</div>;
}
? 2. useContext vs props:區別對比
項目 | props | useContext |
---|---|---|
數據傳遞方式 | 父組件手動一層一層傳遞 | 提供一次,全局可用 |
靈活性 | 更靈活,每個組件單獨定義 | 更全局,統一管理 |
代碼復雜度 | 嵌套層級多時變復雜 | 跨層更簡單,避免“prop drilling” |
場景 | 大多數局部傳值場景 | 全局狀態,如登錄用戶、主題、權限、多語言等 |
性能影響 | 精細控制每一層渲染 | 變更會導致所有消費組件重新渲染(需 memo 優化) |
? 3. useContext + props 混用
const ThemeContext = createContext("light");function Button({ label }) {const theme = useContext(ThemeContext);return <button className={`btn-${theme}`}>{label}</button>;
}function App() {return (<ThemeContext.Provider value="dark"><Button label="點擊我" /></ThemeContext.Provider>);
}
label
是 props 傳遞的內容theme
是 context 提供的“全局數據”
二者結合用是常見寫法。
? 4. useContext + props 高級配合場景舉例
示例:顯示用戶名稱并支持外部傳遞自定義 greeting
const UserContext = createContext({ name: "匿名用戶" });function Welcome({ greeting = "你好" }) {const user = useContext(UserContext);return <h1>{greeting},{user.name}</h1>;
}function App() {return (<UserContext.Provider value={{ name: "小紅" }}><Welcome greeting="歡迎回來" /></UserContext.Provider>);
}
? 5. 注意事項
不推薦把所有數據都放在 context 中,會導致過度渲染。
用 context 的時候,推薦拆小組件 + memo 優化。
可以結合
useReducer + useContext
實現簡易狀態管理(類 Redux)。
? 總結一下
方式 | 說明 |
---|---|
props | 用于組件直接傳遞數據,一層層傳 |
useContext | 用于全局或跨層組件數據共享(主題/用戶/語言) |
混合使用 | 最常見寫法:context 提供環境,props 控制行為 |