官方资料:clsx-for-tailwind – npm。
1. 如何使用?
安装:
npm install clsx-for-tailwind
导入:
import { cn } from "clsx-for-tailwind";
基本用法:
const className = cn(
"text-red-500",
"text-lg",
"font-bold"
);
得到:
text-red-500 text-lg font-bold
2. cn 支持哪些参数?
这个函数不仅支持字符串,还支持对象、数组和条件表达式。
① 字符串
cn("text-red-500", "font-bold")
② 对象
cn({
"text-red-500": true,
"bg-blue-500": false,
"font-bold": true
})
结果:
text-red-500 font-bold
对象的 key 是 CSS 类名,value 是布尔值,只有 value 为 true 的类名才会被保留。
③ 数组
cn([
"text-red-500",
"font-bold",
"bg-blue-500"
])
④ 条件表达式
const isActive = true;
cn(
"text-lg",
isActive && "bg-blue-500"
)
结果:
text-lg bg-blue-500
这些用法都来自该包的 API 设计。
npm+1
3. 最重要的功能:处理 Tailwind CSS 类名冲突
例如:
cn("p-2", "p-4")
结果:
p-4
因为:
p-2:上下左右内边距为 0.5rem。p-4:上下左右内边距为 1rem。
两者设置的是同一个 CSS 属性,后面的 p-4 会取代前面的 p-2。
再看一个例子:
cn("text-red-500", "text-blue-500")
结果:
text-blue-500
同样,后面的文字颜色取代前面的文字颜色。
4. 在 React 组件中使用
这是比较典型的用法:
import { cn } from "clsx-for-tailwind";
interface Props {
active: boolean;
className?: string;
}
function MyButton({ active, className }: Props) {
return (
<button
className={cn(
"px-4 py-2 rounded-md",
active ? "bg-blue-500" : "bg-gray-500",
className
)}
>
提交
</button>
);
}
调用:
<MyButton active={true} className="px-8" />
最终处理后的 className:
px-8 py-2 rounded-md bg-blue-500
这里有三个作用:
- 设置按钮的默认样式。
- 根据
active 动态设置背景颜色。 - 允许外部通过
className 覆盖默认样式。
5. cn 函数的参数类型
该包的 API 定义为:
cn(...inputs: ClassValue[]): string
可以这样理解:
...inputs:接收任意数量的参数。ClassValue[]:每个参数都必须符合 ClassValue 类型。string:最终返回一个字符串。
例如:
cn(
"p-4",
true && "text-red-500",
{
"font-bold": true
},
["rounded", "shadow-md"]
);
特别注意: cn() 不是 React 自带的函数,也不是 Tailwind CSS 自带的函数,而是第三方工具包提供的辅助函数。
你可以把它理解为:专门帮助 React 组件动态管理 Tailwind CSS 类名的工具。