Badge(徽标)
显示徽章或外观类似徽章的组件。
loading
安装
bash
npx shadcn@latest add badge1
1. 将以下代码复制到你的项目中。
tsx
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
const badgeVariants = cva(
"group/badge inline-flex min-h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 type-small whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pe-1.5 has-data-[icon=inline-start]:ps-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-[var(--primary-hover)]",
secondary:
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
destructive:
"bg-destructive/10 text-danger-soft-foreground focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
outline:
"border-border bg-input/30 text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost:
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
render,
...props
}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
return useRender({
defaultTagName: "span",
props: mergeProps<"span">(
{
className: cn(badgeVariants({ variant }), className),
},
props
),
render,
state: {
slot: "badge",
variant,
},
})
}
export { Badge, badgeVariants }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2. 根据你的项目配置调整导入路径。
用法
tsx
import { Badge } from "@/components/ui/badge"1
tsx
<Badge variant="default | outline | secondary | destructive">Badge</Badge>1
变体
使用 variant 属性切换徽章变体。
loading
带图标
可以在徽章内渲染图标。使用 data-icon="inline-start" 将图标放在左侧,使用 data-icon="inline-end" 将图标放在右侧。
loading
带加载指示器
可以在徽章内渲染加载指示器。请为指示器添加 data-icon="inline-start" 或 data-icon="inline-end" 属性。
loading
链接
使用 render 属性将徽章渲染为链接。
loading
自定义颜色
可以向 Badge 组件添加 bg-chart-2/10 text-foreground 等自定义类来调整徽章颜色。
loading
RTL
要在 shadcn/ui 中启用 RTL 支持,请参阅 RTL 配置指南。
loading
API 参考
Badge
Badge 组件显示徽章或外观类似徽章的组件。
| 属性 | 类型 | 默认值 |
|---|---|---|
variant | "default" | "secondary" | "destructive" | "outline" | "ghost" | "link" | "default" |
className | string | - |