我在 NextJS 中创建了一个 ThemeContext 来切换我的网站主题,它可以正常工作,并且在网站初始加载时,我的主体类名称中有“light”类,但我在类名称中使用“dark:”的元素正在应用深色主题而不是初始浅色主题...
这是我的主题按钮:
const ThemeButton = () => {
const { theme, setTheme } = useTheme();
return (
<button
className="text-primary dark:bg-containerDark bg-containerLight flex justify-center items-center w-12 h-12 rounded-xl"
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
>
{theme === "light" ? (
<FaMoon className="w-5 h-5" />
) : (
<PiSunDimFill className="w-5 h-5" />
)}
</button>
);
};
export default ThemeButton;
这是“加载”上的按钮,如您所见,我有浅色类,“深色:”在按钮的类中是正确的:
如果你想看的话,这是我的 themeContext :
"use client";
import React, { createContext, useContext, useEffect, useState } from "react";
type Theme = "light" | "dark";
interface ThemeContextType {
theme: Theme;
setTheme: (theme: Theme) => void;
}
const ThemeContext = createContext<ThemeContextType | undefined>({
theme: "light",
setTheme: () => {},
});
export const useTheme = (): ThemeContextType => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
};
export const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
const [theme, setTheme] = useState<Theme>("light");
// Update the body class when theme changes
useEffect(() => {
document.body.classList.remove("light", "dark");
document.body.classList.add(theme);
}, [theme]);
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
目前,似乎
dark:-
类正在通过系统的prefers-color-scheme
而不是身体上的dark
或light
类来识别黑暗主题。
您可以尝试配置 tailwind 以使用
dark
和 light
类手动切换暗模式,如下所示:
https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually