You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中如何使用daisyUI与TailwindCSS实现亮暗主题切换

React 项目集成 daisyUI + TailwindCSS 实现亮暗主题一键切换

第一步:修改 Tailwind 配置文件

打开项目根目录的tailwind.config.js,补充暗色模式配置和daisyUI主题注册:

/** @type {import('tailwindcss').Config} */
export default {
  darkMode: 'class',
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [require("daisyui")],
  daisyui: {
    themes: ["light", "dark"],
  }
}

多数人配置不生效的核心原因是没开darkMode: 'class',也没在daisyui配置项里注册要用到的主题。

第二步:实现主题切换按钮组件

直接复用下面的组件代码即可,自带本地存储持久化、系统主题初始化逻辑,不会出现页面加载闪屏问题:

import { useEffect, useState } from 'react'

const ThemeToggle = () => {
  const [isDark, setIsDark] = useState(() => {
    const saved = localStorage.getItem('app-theme')
    if (saved) return saved === 'dark'
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  })

  useEffect(() => {
    const root = document.documentElement
    if (isDark) {
      root.classList.add('dark')
      root.setAttribute('data-theme', 'dark')
      localStorage.setItem('app-theme', 'dark')
    } else {
      root.classList.remove('dark')
      root.setAttribute('data-theme', 'light')
      localStorage.setItem('app-theme', 'light')
    }
  }, [isDark])

  return (
    <button 
      className="btn btn-circle btn-ghost"
      onClick={() => setIsDark(prev => !prev)}
      aria-label="切换主题"
    >
      {isDark ? (
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>
      ) : (
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/></svg>
      )}
    </button>
  )
}

export default ThemeToggle

关键注意点

  • daisyUI的主题样式完全依赖html根标签的data-theme属性控制,必须和Tailwind的dark类同步修改,否则会出现组件样式和自定义dark:前缀样式不匹配的问题
  • 主题初始化逻辑要写在useState的初始化回调里,保证页面渲染前就读取到正确的主题配置,避免闪屏
  • 组件可以直接放到导航栏等全局位置,点击就能完成亮/暗色模式切换,刷新页面后会保留用户上次选择的主题

内容的提问来源于stack exchange,提问作者kmurp62rulz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 02:02:18