React + Tailwind css V4:从零实现流畅的动态主题

React + Tailwind css V4:从零实现流动态主题配置与切换

在这里插入图片描述

Tailwindcss4官网 文档

1.项目初始化

首先,我们用vite搭建一个 React 项目,并安装 Tailwind CSS

npm create vite@latest my-theme-app --template react
cd my-theme-app
npm install
npm install tailwindcss @tailwindcss/vite

然后,在 vite.config.js 中添加tailwind配置

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'

export default defineConfig({
  plugins: [react(), tailwindcss()],
})

由于版本4不需要config配置文件,但是导致编辑器会没有代码提示,所以复制一个版本3里面的tailwind.config.js

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

tailwind4 样式引入

//index.css

@import "tailwindcss";

//主题样式 配置。。。

2.主题切换逻辑

删除多余代码 留个React svg 表当作 切换的 Btn
创建一个ThemeProvider组件来管理深浅色模式,包裹App组件

import { ThemeProvider } from './ThemeProvider.js'
createRoot(document.getElementById('root')).render(
  <StrictMode>
    <ThemeProvider>
      <App />
    </ThemeProvider>
  </StrictMode>,
)

补充 App 组件,样式如下


import reactLogo from './assets/react.svg'
import { useTheme } from "./ThemeProvider";
function App() {
  const { theme, setTheme } = useTheme();
  return (
    <main className='w-screen h-screen flex flex-col items-center justify-center '>
      <h1 className={`text-2xl`}>Vite + React</h1>
      <a href="#" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
        <img src={reactLogo} className="logo react" alt="React logo" />
      </a>
    </main>
  )
}

export default App

在这里插入图片描述
此时 在浏览器中点击react图标 F12查看 html标签的css类 会切换dark/light

坚持一下 马上就要成功了!!!

3. 主题适配样式

@import 'tailwindcss';

* {
  padding: 0;
  margin: 0;
}

@theme {
  --color-theme-bg: var(--color-bg);
  --color-theme-text: var(--color-text);
}

@custom-variant dark (&:where(.dark, .dark *));
@custom-variant light (&:where(.light, .light *));

@layer base {
  .light {
    --color-bg: #edf2ee;
    --color-text: #171717;
  }

  .dark {
    --color-bg: #171717;
    --color-text: #edf2ee;
  }
}

颜色配置完 ,记得补充App组件

// ... 表示忽略部分
<main className='...  bg-theme-bg'>
<h1 className={`... text-theme-text`}>Vite + React</h1>

成功了 , 黑白主题风!

在这里插入图片描述

发布第二天!! 发现忘记给 provider 代码 !!自己封装一个最简单的ThemeProvider

ThemeProvider

import React, { createContext, useContext, useEffect, useState } from "react";

interface ThemeContextType {
  theme: string;
  setTheme: (theme: string) => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
  const storedTheme =
    typeof window !== "undefined" ? localStorage.getItem("theme") : null;
  const systemPrefersDark =
    typeof window !== "undefined" &&
    window.matchMedia("(prefers-color-scheme: dark)").matches;

  const [theme, setThemeState] = useState<string>(
    storedTheme || (systemPrefersDark ? "dark" : "light")
  );

  useEffect(() => {
    document.documentElement.classList.remove("light", "dark");
    document.documentElement.classList.add(theme);
    localStorage.setItem("theme", theme);
  }, [theme]);

  const setTheme = (newTheme: string) => {
    setThemeState(newTheme);
  };

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error("useTheme must be used within a ThemeProvider");
  }
  return context;
};
<think>好的,我需要帮助用户验证TailwindCSS在WebStorm中是否正确配置并能正常使用。首先,用户的问题是关于如何检查配置是否成功,所以我得一步步引导他们进行验证。 首先,用户可能已经按照之前的引用安装了TailwindCSS和相关依赖,比如引用[1]提到的npm install命令。所以第一步应该是确认依赖是否安装正确。用户需要检查package.json里是否有tailwindcss和@types/tailwindcss,并且版本是否合适。这一步很重要,因为如果依赖没装好,后续的步骤都会有问题。 接下来,用户需要确认配置文件是否存在。TailwindCSS通常需要tailwind.config.js和postcss.config.js。根据引用[3],用户可能在src目录下创建了main.css,里面包含了@tailwind指令。这时候需要检查这些配置文件是否正确,特别是content属性是否包含了项目中的文件路径,否则样式可能不会生效。 然后是CSS文件的引入情况。用户可能在main.css里写了基础的Tailwind指令,但如果在项目中没正确引入这个CSS文件,样式也不会生效。比如在Vue或React项目中,需要在入口文件导入这个CSS,所以需要检查是否有这样的导入语句。 接下来是IDE的功能验证。引用[4]提到WebStorm现在支持Tailwind类的自动完成,尤其是在HTML文件和@apply指令后。用户可以在HTML中输入一个Tailwind类,比如text-red-500,看看是否有代码补全的提示。如果有,说明WebStorm已经识别了Tailwind的配置。 然后是编译检查。用户需要运行项目,查看控制台是否有Tailwind相关的错误。如果有,可能是配置问题或者版本冲突。同时,在浏览器中检查元素,看看应用的Tailwind类是否被正确编译成CSS样式。如果类名存在但没有样式,可能是编译过程出了问题。 最后,用户可能想进行功能测试,比如创建一个使用Tailwind样式的元素,看看是否能正确显示。比如添加一个按钮,使用bg-blue-500和text-white类,观察按钮是否变成蓝底白字。 如果以上步骤都通过,说明TailwindCSS配置正确。如果有问题,用户需要根据错误提示逐步排查,比如检查配置文件路径、内容是否正确,或者重新安装依赖。同时,提醒用户注意TailwindCSS版本,引用[2]提到v4有改进,可能需要不同的配置方式,所以版本兼容性也需要考虑。 总结来说,我需要分步骤引导用户检查安装、配置、IDE支持、编译结果和实际效果,每个步骤都给出具体的验证方法,并引用相关的帮助文档或之前的引用内容,确保用户能系统地进行验证。</think>### 分步验证 TailwindCSS 在 WebStorm 中的配置 #### 1. **检查依赖安装** - 确认 `package.json` 中是否包含以下依赖(参考引用[1]): ```json "devDependencies": { "tailwindcss": "^3.x.x", "@types/tailwindcss": "^x.x.x", "postcss": "^8.x.x" } ``` - 如果未安装,运行: ```bash npm install -D tailwindcss @types/tailwindcss postcss autoprefixer ``` #### 2. **验证配置文件** - 确保项目根目录存在 `tailwind.config.js` 且配置了内容路径(如引用[3]的`./src/main.css`): ```javascript module.exports = { content: ["./src/**/*.{html,js,vue}"], // 根据项目类型调整文件扩展名 theme: { extend: {} }, plugins: [] } ``` - 检查 `postcss.config.js` 是否包含 TailwindCSS 插件: ```javascript module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } } ``` #### 3. **IDE 功能验证** - 在 HTML/Vue/JSX 文件中输入 Tailwind 类名(如 `text-red-500`),观察是否触发 **代码自动补全**(引用[4]) - 在 CSS 文件中使用 `@apply` 指令时,检查是否支持类名联想: ```css .custom-button { @apply bg-blue-500 text-white; /* 输入@apply后应弹出Tailwind类建议 */ } ``` #### 4. **编译结果检查** - 运行项目构建命令(如 `npm run dev`),观察控制台是否出现 Tailwind 相关错误 - 在浏览器中打开开发者工具,检查元素的 `class` 属性是否被转换为具体样式 例如:`class="text-lg"` 应映射到 `font-size: 1.125rem; line-height: 1.75rem;` #### 5. **功能测试** - 创建测试元素: ```html <div class="p-4 bg-green-100 text-green-800 rounded-lg"> TailwindCSS 运行正常 ✅ </div> ``` - 如果显示为 **浅绿色背景+深绿色文字+圆角**,则配置成功 ### 常见问题排查 | 现象 | 解决方案 | |---------------------|----------------------------------| | 无代码补全 | 检查 WebStorm 的 `Tailwind CSS` 插件是否启用(设置 > Languages & Frameworks > Tailwind CSS) | | 样式未生效 | 确认 `tailwind.config.js` 的 `content` 路径覆盖了目标文件[^3] | | 控制台报版本冲突 | 升级 TailwindCSS 到 v3.x 或参考引用[2]尝试 v4 新配置方式 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值