如何在React项目中基于Tailwind v4.0实现暗黑模式与主题切换
基于Tailwind v4.0 + React实现暗黑模式与主题切换完整流程
Tailwind v4.0改用CSS变量驱动架构,和旧版配置逻辑差异较大,以下是落地完整步骤:
1. 初始化项目并安装依赖
未创建React项目的话先执行:
npx create-react-app tailwind-theme-switch cd tailwind-theme-switch
安装Tailwind v4及配套工具:
npm install tailwindcss@latest postcss@latest autoprefixer@latest
2. 配置Tailwind v4
生成Tailwind配置文件:
npx tailwindcss init
修改tailwind.config.js,启用class模式暗黑模式,可自定义主题色:
/** @type {import('tailwindcss').Config} */ export default { darkMode: 'class', // 核心:用class策略手动控制暗黑模式 content: [ "./src/**/*.{js,jsx,ts,tsx}", ], theme: { extend: { colors: { primary: { light: '#3b82f6', dark: '#1d4ed8', }, }, }, }, plugins: [], }
3. 配置CSS入口文件
在src/index.css中添加Tailwind指令及自定义主题变量:
@tailwind base; @tailwind components; @tailwind utilities; /* 浅色主题变量 */ :root { --color-bg: #ffffff; --color-text: #111827; --color-primary: #3b82f6; } /* 暗黑主题变量覆盖 */ .dark { --color-bg: #111827; --color-text: #f3f4f6; --color-primary: #1d4ed8; } /* 全局样式绑定变量,添加过渡动画 */ body { @apply bg-[--color-bg] text-[--color-text] transition-colors duration-300; }
4. 实现React主题切换逻辑
4.1 创建主题Context
新建src/contexts/ThemeContext.jsx:
import { createContext, useContext, useEffect, useState } from 'react'; const ThemeContext = createContext(); export function ThemeProvider({ children }) { const [theme, setTheme] = useState('light'); // 初始化:优先读localStorage,其次匹配系统深色偏好 useEffect(() => { const savedTheme = localStorage.getItem('theme'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; const initialTheme = savedTheme || (prefersDark ? 'dark' : 'light'); setTheme(initialTheme); document.documentElement.classList.toggle('dark', initialTheme === 'dark'); }, []); // 切换主题函数 const toggleTheme = () => { const newTheme = theme === 'light' ? 'dark' : 'light'; setTheme(newTheme); document.documentElement.classList.toggle('dark', newTheme === 'dark'); localStorage.setItem('theme', newTheme); }; return ( <ThemeContext.Provider value={{ theme, toggleTheme }}> {children} </ThemeContext.Provider> ); } // 自定义钩子简化组件调用 export function useTheme() { return useContext(ThemeContext); }
4.2 挂载ThemeProvider
修改src/index.jsx,用ThemeProvider包裹根组件:
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import { ThemeProvider } from './contexts/ThemeContext'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <ThemeProvider> <App /> </ThemeProvider> </React.StrictMode> );
4.3 编写主题切换按钮
新建src/components/ThemeSwitch.jsx:
import { useTheme } from '../contexts/ThemeContext'; export default function ThemeSwitch() { const { theme, toggleTheme } = useTheme(); return ( <button onClick={toggleTheme} className="px-4 py-2 rounded-full bg-primary text-white dark:bg-primary-dark transition-all" aria-label={`切换到${theme === 'light' ? '暗黑' : '浅色'}模式`} > {theme === 'light' ? '🌙 暗黑模式' : '☀️ 浅色模式'} </button> ); }
5. 页面中使用测试
修改src/App.jsx:
import ThemeSwitch from './components/ThemeSwitch'; import { useTheme } from './contexts/ThemeContext'; function App() { const { theme } = useTheme(); return ( <div className="min-h-screen flex flex-col items-center justify-center p-8"> <h1 className="text-3xl font-bold mb-8 text-primary dark:text-primary-dark"> Tailwind v4 主题切换示例 </h1> <p className="mb-6">当前主题:{theme}</p> <ThemeSwitch /> </div> ); } export default App;
关键提示
- 必须配置
darkMode: 'class'才能通过DOM类切换暗黑模式,这是Tailwind v4手动切换的核心 - 自定义CSS变量配合Tailwind的
[--variable]语法,可实现更灵活的多主题扩展 - 用localStorage持久化主题选择,避免刷新后重置
- 添加
transition-colors类实现平滑切换动画
内容的提问来源于stack exchange,提问作者Abdul Rehman
相关产品推荐
相关产品推荐

