react 下 使用Tailwind CSS 来进行页面颜色切换
要做什么
比如你使用react编写了一个网页,现在你要完成切换页面主题的功能,具体来说就是:
-
当切换到深色主题,背景色加深,文字颜色变浅
-
当切换到浅色主题,背景色变浅,文字颜色加深
辩证 使用使用 tailwind CSS 完成该功能的优缺点
优点
-
简单
-
特别简单
缺点
- 不知道,爱谁谁
需要什么
- Tailwind Css
步骤
-
react开发环境的安装和 tailwind依赖安装 (这里请参照tailwind文档的设置)
-
tailwind Css的基础配置
-
config文件配置
1. 配置 `content: ["./src/**/*.{js,jsx,ts,tsx}"]`,告知tailwind 项目文件在哪个目录
2. 配置 `darkMode: "class"` ,告知tailwind我想手动切换颜色模式
- css文件配置(引入tailwind的样式文件)
切换背景色和文字颜色的CSS配置
- 在index.css中添加如下内容
/* 切换 color mode */
.color-change-base {
@apply bg-gray-100 text-black dark:bg-blue-900 dark:text-white;
}
-
color-change-base 是自定义的类名,任何需要设置切换颜色主题功能的组件,只要加上了这个类名,就能完成颜色切换。
-
bg-gray-100 text-black dark:bg-blue-900 dark:text-whit 是tailwind Css提供的工具类
-
因为这些类的功能性极强,比如 bg-gray-100 就是设置背景颜色为 灰色-不透明度100
-
注意 bg-gray-100 text-black 和dark:bg-blue-900 dark:text-white 这一组,前面两个是浅色模式下,背景颜色灰色,文字黑色,后两个是 深色模式下背景颜色蓝色,文字颜色白色
-
-
@apply 是告诉 tailwind ,请把后边一长串功能类提供的功能传递给 color-change-base这个类名
具体使用到组件/页面
-
在需要使用颜色切换的组件上 添加 color-change-base类名
-
当使用 class 模式(tailwind.config.js文件中的设置),在html标签添加或删除 dark类名,就能完成页面的颜色模式切换
切换逻辑
请查看tailwind CSS官网
// On page load or when changing themes, best to add inline in `head` to avoid FOUC
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
// Whenever the user explicitly chooses light mode
localStorage.theme = 'light'
// Whenever the user explicitly chooses dark mode
localStorage.theme = 'dark'
// Whenever the user explicitly chooses to respect the OS preference
localStorage.removeItem('theme')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探