Skip to content

useContext

useContext可以用来读取和订阅组件中的Context。

基本用法

Context可以向组件树的深层传递状态。

useContext()可以在组件树中向上寻找最近的Context.Provider

如果需要通过Context更新传递的数据,则需要结合state使用。

ts
import { createContext } from "react";

export const UseContextTheme = createContext({
    theme: "light",
    setTheme: (_theme: string | ((theme: string) => any)) => {}
});
tsx
import { useContext, useState } from "react";
import { UseContextTheme } from "./UseContextTheme";

function ButtonComponent({ children }: { children: React.ReactNode }) {
    const { theme, setTheme } = useContext(UseContextTheme);

    const currentTheme = {
        backgroundColor: theme === "light" ? "#fff" : "#333",
        color: theme === "light" ? "#000" : "#fff"
    };

    return (
        <div style={currentTheme}>
            <p>当前主题是:{theme}</p>
            <button onClick={
                () => setTheme(pre => pre === "light" ? "dark" : "light")
            }>
                {children}
            </button>
        </div>
    );
}

function FormComponent() {
    return <ButtonComponent>切换主题</ButtonComponent>;
}

export default function UseContextBasic() {
    const [theme, setTheme] = useState("light");
    return (
        <UseContextTheme.Provider value={{ theme, setTheme }}>
            <FormComponent />
        </UseContextTheme.Provider>
    );
}