SuperAPI AI 工具集

shadcn-ui

前端与建站

查看项目

更新于 10-15 15:47

技能介绍

用途

shadcn/ui 是一套使用 Radix UI 原语构建、Tailwind CSS 样式化的可复用 React 组件集合。与传统组件库不同,它的组件被直接复制进项目中,让开发者拥有完整的代码所有权与定制控制权。组件具备无障碍特性、可定制且开源。

其核心理念是:复制粘贴组件,而不是安装 npm 包——你拥有代码。

主要能力

  • 提供使用 Radix UI 无障碍原语构建、Tailwind CSS 样式化的 React 组件
  • 组件直接复制到项目的 components/ui/ 目录,可完全定制
  • TypeScript 优先
  • 开箱支持深色模式
  • 使用 CSS 变量进行主题化
  • 采用组合优于配置的方式

使用方式

初始化项目:

npx shadcn-ui@latest init

随后根据交互提示选择 TypeScript、样式(Default/New York)、基础色(Slate/Gray/Zinc/Neutral/Stone)、CSS 变量、React Server Components 等选项。

添加组件:

npx shadcn-ui@latest add button
npx shadcn-ui@latest add card
npx shadcn-ui@latest add dialog

也可一次添加多个组件:

npx shadcn-ui@latest add button card dialog form input

基本用法示例:

import { Button } from "@/components/ui/button"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"

export default function Example() {
  return (
    <Card>
      <CardHeader>
        <CardTitle>Welcome</CardTitle>
      </CardHeader>
      <CardContent>
        <Button>Click me</Button>
      </CardContent>
    </Card>
  )
}

技术栈

核心依赖包括 Radix UI(无障碍组件原语,无头 UI)、Tailwind CSS(工具优先样式)、TypeScript(类型安全)、class-variance-authority(CVA,变体管理)、clsx(类名拼接)与 tailwind-merge(无冲突类名合并)。

配置

组件通过 components.json 配置,关键选项包括:

  • style:"default" 或 "new-york"(设计变体)
  • rsc:React Server Components 支持
  • cssVariables:使用 CSS 变量进行主题化
  • prefix:Tailwind 类前缀(可选)
{
  "$schema": "https://ui.shadcn.com/schema.json",
  "style": "default",
  "rsc": true,
  "tsx": true,
  "tailwind": {
    "config": "tailwind.config.ts",
    "css": "app/globals.css",
    "baseColor": "slate",
    "cssVariables": true,
    "prefix": ""
  },
  "aliases": {
    "components": "@/components",
    "utils": "@/lib/utils",
    "ui": "@/components/ui",
    "lib": "@/lib",
    "hooks": "@/hooks"
  }
}

组件目录

通过 CLI 可用的组件包括:accordion、alert、alert-dialog、avatar、badge、calendar、checkbox、command(⌘K 命令面板)、context-menu、dropdown-menu、hover-card、input、label、menubar、navigation-menu、popover、progress、radio-group、scroll-area、select、separator、sheet、skeleton、slider、switch、tabs、textarea、toast、toggle、tooltip 等。

主题化

可通过重新初始化更换基础配色,或手动在 globals.css 中覆盖 CSS 变量:

:root {
  --primary: 210 100% 50%;  /* HSL: Blue */
  --primary-foreground: 0 0% 100%;
}

.dark {
  --primary: 210 100% 60%;  /* Lighter blue for dark mode */
}

也可通过 CVA 扩展自定义变体,并结合 next-themes 实现主题切换。

适用场景

  • 使用 Tailwind CSS 构建 React 应用
  • 需要无障碍、可投入生产的 UI 组件
  • 希望对组件代码和样式拥有完全控制
  • 偏好组合而非配置
  • 使用 Next.js、Vite、Remix 或 Astro 构建
  • 需要开箱即用的深色模式支持
  • 需要 TypeScript 优先的组件

限制

  • 不使用 Tailwind CSS 时不适用(核心样式依赖)
  • 需要旧版浏览器支持时不适用(使用了现代 CSS 特性)
  • 偏好打包 npm 库而非代码所有权时不适用
  • 构建非 React 框架(Vue、Svelte、Angular)时不适用