React Tailwind CSS

传统 CSS 要起类名、来回翻文件、担心冲突;Tailwind 反其道而行——不写样式表,直接在 className 里堆「工具类」,类名即样式。改样式不用离开 JSX,它已成为 React 生态中最流行的样式方案之一。本节以 Tailwind v4 + Vite 为例讲解。

认识工具类

下面这行是完整的 Tailwind 写法,每个类只做一件事:

<button className="rounded bg-blue-500 px-4 py-2 text-white">
  确认
</button>

对照含义:rounded 是圆角,bg-blue-500 是蓝色背景,px-4 左右内边距、py-2 上下内边距,text-white 白色文字。全程不用写一行 CSS,类名本身就是说明书。

安装(Vite + Tailwind v4)

安装 Tailwind 与官方 Vite 插件:

npm install tailwindcss @tailwindcss/vite

在 vite.config.js 里注册插件:

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

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

在入口样式文件里引入 Tailwind:

@import "tailwindcss";

拼装一张卡片

工具类可以自由组合,快速搭出完整界面,悬停等交互状态也是「前缀 + 类名」的写法。

export default function Card({ title, desc }) {
  return (
    <div className="max-w-sm rounded-lg border border-gray-200 p-4 shadow-sm">
      <h2 className="text-lg font-bold text-gray-800">{title}</h2>
      <p className="mt-2 text-sm text-gray-500">{desc}</p>
      <button className="mt-4 rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600">
        查看详情
      </button>
    </div>
  );
}
// hover:bg-blue-600 表示鼠标悬停时背景加深

条件类名与响应式布局

需要动态变化的样式用三元或模板字符串拼接;响应式靠前缀,如 md: 表示中等屏幕及以上生效。

export default function Grid({ items }) {
  return (
    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
      {items.map((item) => (
        <div key={item.id} className={item.hot ? 'bg-amber-100' : 'bg-white'}>
          {item.name}
        </div>
      ))}
    </div>
  );
}
// 手机端 1 列,md 宽度及以上自动变成 2 列

小结

Tailwind 的思路是「用工具类拼装界面」:背景、间距、圆角都有现成类名;hover:/md:/dark: 等前缀解决交互与响应式;需要变化的地方用三元表达式控制。重复的工具类串抽成组件,样式就能长期保持整洁。

笔记加载中…