ReactJS Hook 模式 ~使用 Hook 与 Context~
发布: (2026年1月16日 GMT+8 16:56)
1 min read
原文: Dev.to
Source: Dev.to

使用 use Hook 与 Context
- 在 ReactJS 19 中,引入了
useHook,以提供比useContextHook 更灵活的读取 Context 值的方式。 useHook 可以在if语句和循环内部有条件地调用,使其非常适合在组件中实现动态行为。
import { createContext, useContext, use } from "react";
import "./app.css";
const ThemeContext = createContext(null);
function Button({ show, children }) {
if (show) {
const theme = use(ThemeContext);
const className = "button-" + theme;
return { children };
}
return null;
}
function App() {
return (
<div>
{/* UI elements go here */}
</div>
);
}
export default App;
在 Context 中使用 Hook
(原文在代码片段后包含了此标题。)