import { createContext, useContext, useState } from "react";
import { Button } from "./components/ui/button";
interface IThemeContext {
setTheme: (theme: string) => void;
const ThemeContext = createContext<IThemeContext>({
const [theme, setTheme] = useState("light");
<ThemeContext value={{ theme, setTheme }}>
<h1 className="text-2xl font-bold mb-4">父组件</h1>
<Button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
function ChildComponent() {
// 2. 在子组件中使用 useContext 获取上下文值
const { theme, setTheme } = useContext(ThemeContext);
<h2 className="text-xl font-bold mb-2">子组件</h2>
<Button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>