1.下載插件
npm install --save @emotion/css
2.創建ThemeContext.tsx
// src/ThemeContext.tsx
import React, { createContext, useContext, useState } from "react";// 定義主題類型
export type Theme = "light" | "dark";// 定義主題上下文的類型
interface ThemeContextType {theme: Theme;toggleTheme: () => void;
}// 創建主題上下文
export const ThemeContext = createContext<ThemeContextType | undefined>(undefined);// 創建一個主題提供器組件
export const ThemeProvider: React.FC = ({ children }) => {const [theme, setTheme] = useState<Theme>("light"); // 默認主題為 'light'const toggleTheme = () => {setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));};return <ThemeContext.Provider value={{ theme, toggleTheme }}>{children}</ThemeContext.Provider>;
};// 創建一個自定義鉤子來方便使用主題上下文
export const useTheme = () => {const context = useContext(ThemeContext);if (!context) {throw new Error("useTheme must be used within a ThemeProvider");}return context;
};
3.創建themeConfig.ts配置主題顏色文件
//themeConfig.ts
import { Theme } from "./ThemeContext";export const themes = {light: {backgroundColor: "#ffffff",color: "green",primaryColor: "#007bff",secondaryColor: "#6c757d",},dark: {backgroundColor: "#333333",color: "red",primaryColor: "#007bff",secondaryColor: "#6c757d",},
};export const getTheme = (theme: Theme) => themes[theme];
4.在app.tsx 掛載
import { ThemeProvider } from "@/theme/ThemeContext";const App = () => {return (<ThemeProvider><div>App<div></ThemeProvider>);
};export default observer(App);
6.使用直接寫樣式方式一
// @live
import { useEffect } from "react";
import { css, cx } from "@emotion/css";
import { useTheme } from "@/theme/ThemeContext";
import { getTheme } from "@/theme/themeConfig";
import "./index.less";
const ThemeBox: any = () => {const { theme, toggleTheme } = useTheme();const currentTheme = getTheme(theme);const styles = css`background-color: ${currentTheme.color};`;return (<div className={cx("cockpit-contain", styles)} onClick={toggleTheme}></div>);
};export default ThemeBox;
6.使用類名方式二
// @live
import { useEffect } from "react";
import { css, cx } from "@emotion/css";
import { useTheme } from "@/theme/ThemeContext";
import { getTheme } from "@/theme/themeConfig";
import "./index.less";
const ThemeBox: any = () => {const { theme, toggleTheme } = useTheme();const currentTheme = getTheme(theme);const styles = css`.background {background-color: ${currentTheme.background};}.boder-color {border-color: ${currentTheme.borderColor};}`;return (<div className={cx("cockpit-contain", styles)} onClick={toggleTheme}><div className={"background"}></div><div className={"boder-color"}></div></div>);
};export default ThemeBox;