aui-components
ComponentsUtilities

cn

clsx + tailwind-merge 类名合并工具函数

cn 是一个使用 clsx 和 tailwind-merge 组合的工具函数,用于安全地合并 Tailwind CSS 类名。

引入

import { cn } from "aui-components";

基本用法

const className = cn(
  "text-sm font-medium", // 基础类
  isActive && "text-primary", // 条件类
  className, // 外部传入类
);

Props

未找到组件元数据: cn

功能

clsx — 灵活的条件类名

cn("text-red-500", false && "hidden", "p-4");
// => "text-red-500 p-4"

cn(["flex", "items-center"], { "opacity-50": disabled });
// => "flex items-center opacity-50"

tailwind-merge — 智能合并 Tailwind 冲突

// 后面的类会覆盖前面的冲突
cn("px-2 py-1", "px-4");
// => "py-1 px-4"

cn("text-red-500", "text-blue-500");
// => "text-blue-500"

cn("bg-red-500 bg-opacity-50", "bg-blue-500");
// => "bg-blue-500"

在组件库中的使用

cn 是 aui-components 中最基础的工具函数,所有组件都使用它来合并样式:

// button.tsx
<Button className={cn(buttonVariants({ variant, size }), className)} />

// tooltip.tsx
<TooltipPrimitive.Popup className={cn("z-50 inline-flex ...", className)} />

// image.tsx
<div className={cn(imageVariants({ variant, size, className }))} />

// thread.tsx
<div className={cn("flex flex-1 flex-col ...", isEmpty && "justify-center")} />

实现

import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
  • clsx 处理条件类名、数组、对象
  • twMerge 解析 Tailwind 类名,智能解决冲突
  • 组合使用确保类名正确且无冗余

On this page