使用 Tailwind v4 与 next-themes 实现暗黑模式

发布: (2026年1月11日 GMT+8 03:10)
3 min read
原文: Dev.to

Source: Dev.to

安装

npm install next-themes

main.jsx 中设置

import { ThemeProvider } from "next-themes";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

createRoot(document.getElementById("root")).render(
  
  
    
  
  
);

Provider 属性

属性描述
attribute="class"为 “ 元素添加 dark
defaultTheme="system"默认使用系统偏好
enableSystem自动检测系统主题
storageKey="theme-name"(可选) 自定义 localStorage

Tailwind CSS 配置

@import "tailwindcss";

/* 启用 dark 变体 */
@variant dark (&:is(.dark *));

/* 定义自定义颜色标记 */
@theme {
  --color-primary: light-dark(#10b981, #dc2626);
  --color-surface: light-dark(#f8fafc, #0f172a);
}

颜色标记语法

--color-[name]: light-dark([light-color], [dark-color]);

示例

--color-primary: light-dark(#10b981, #dc2626);

在 JSX 中使用标记

Hello

Content

注意: 变量名中 不要 包含 text-bg- 前缀;Tailwind 会自动添加这些前缀。

主题切换组件

import { useTheme } from "next-themes";
import { useEffect, useState } from "react";

function ThemeToggle() {
  const { theme, setTheme } = useTheme();
  const [mounted, setMounted] = useState(false);

  // 防止 SSR 渲染不匹配
  useEffect(() => setMounted(true), []);

  if (!mounted) return null;

  return (
     setTheme(theme === "dark" ? "light" : "dark")}>
      Toggle Theme
    
  );
}

没有挂载守卫的最小版本:

import { useTheme } from "next-themes";

function ThemeToggle() {
  const { theme, setTheme } = useTheme();

  return (
     setTheme(theme === "dark" ? "light" : "dark")}>
      {theme === "dark" ? "🌙" : "☀️"}
    
  );
}

useTheme API 参考

const { theme, setTheme, systemTheme, themes } = useTheme();
属性类型描述
themestring当前主题:"light""dark""system"
setTheme(name)function更改主题
systemThemestring系统偏好:"light""dark"
themesarray可用的主题列表

扩展颜色标记

@theme {
  /* 背景 */
  --color-surface: light-dark(#f8fafc, #0f172a);
  --color-card: light-dark(#ffffff, #1e293b);

  /* 文本 */
  --color-primary: light-dark(#1f2937, #f9fafb);
  --color-secondary: light-dark(#6b7280, #9ca3af);

  /* 品牌 */
  --color-brand: light-dark(#10b981, #34d399);
  --color-accent: light-dark(#3b82f6, #60a5fa);
}

故障排除

  • 暗模式未激活

    • 确认 “ 在 DevTools 中出现。
    • 清除 localStorage 并刷新页面。
    • 确保编译后的 CSS 中包含 @variant dark (&:is(.dark *)); 规则。
  • 颜色未变化

    • 不要在自定义颜色变量名中包含 text-bg-
    • 使用正确的 light-dark 语法,例如 light-dark(#fff, #000)

快速参考

// 设置

// 切换主题
const { theme, setTheme } = useTheme();
setTheme(theme === "dark" ? "light" : "dark");

// 定义颜色
--color-primary: light-dark(#10b981, #dc2626);

// 使用颜色

链接

Back to Blog

相关文章

阅读更多 »