Tailwind CSS 实战技巧
组件提取的时机
Tailwind 的原子类方式初看会让 HTML 很冗长。正确的应对方式不是过早提取 class,而是提取组件:
// ❌ 错误:用 @apply 提取工具类
.btn-primary {
@apply px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700;
}
// ✅ 正确:提取 React 组件
function Button({ children, ...props }: ButtonProps) {
return (
<button
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
{...props}
>
{children}
</button>
);
}
自定义主题
在 CSS 文件中定义设计令牌:
@import "tailwindcss";
@theme {
--color-brand-50: oklch(0.97 0.01 264);
--color-brand-500: oklch(0.55 0.22 264);
--color-brand-900: oklch(0.25 0.12 264);
--font-sans: "Geist Variable", system-ui, sans-serif;
--radius-card: 12px;
}
条件样式的最佳实践
使用 clsx 或 cn 管理条件类名:
import { clsx } from "clsx";
function Badge({ variant }: { variant: "success" | "error" | "warning" }) {
return (
<span className={clsx(
"px-2 py-0.5 rounded-full text-sm font-medium",
variant === "success" && "bg-green-100 text-green-800",
variant === "error" && "bg-red-100 text-red-800",
variant === "warning" && "bg-yellow-100 text-yellow-800",
)}>
{/* ... */}
</span>
);
}
总结
Tailwind 的设计哲学是"工具类优先",但这不意味着放弃组件化。将设计系统表达为设计令牌,将 UI 模式封装为组件,才是在大型项目中驾驭 Tailwind 的正确姿势。