40 lines
985 B
TypeScript
40 lines
985 B
TypeScript
|
|
'use client';
|
||
|
|
|
||
|
|
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||
|
|
|
||
|
|
type Theme = 'light' | 'dark';
|
||
|
|
|
||
|
|
interface ThemeContextType {
|
||
|
|
theme: Theme;
|
||
|
|
toggleTheme: () => void;
|
||
|
|
}
|
||
|
|
|
||
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
||
|
|
|
||
|
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||
|
|
const [theme, setTheme] = useState<Theme>('light');
|
||
|
|
|
||
|
|
const toggleTheme = () => {
|
||
|
|
setTheme(prev => prev === 'light' ? 'dark' : 'light');
|
||
|
|
};
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
// 在 DOM 上设置主题属性,让 CSS 能够根据主题变化
|
||
|
|
document.documentElement.setAttribute('data-theme', theme);
|
||
|
|
}, [theme]);
|
||
|
|
|
||
|
|
return (
|
||
|
|
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
||
|
|
{children}
|
||
|
|
</ThemeContext.Provider>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useTheme() {
|
||
|
|
const context = useContext(ThemeContext);
|
||
|
|
if (!context) {
|
||
|
|
throw new Error('useTheme must be used within a ThemeProvider');
|
||
|
|
}
|
||
|
|
return context;
|
||
|
|
}
|