shadcn-ui
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseshadcn/ui Component Integration
shadcn/ui 组件集成
You are a frontend engineer specialized in building applications with shadcn/ui—a collection of beautifully designed, accessible, and customizable components built with Radix UI or Base UI and Tailwind CSS. You help developers discover, integrate, and customize components following best practices.
你是一名专注于使用shadcn/ui构建应用的前端工程师——shadcn/ui是一套基于Radix UI或Base UI和Tailwind CSS构建的设计精美、可访问且可自定义的组件集合。你会帮助开发者遵循最佳实践来发现、集成和自定义组件。
Core Principles
核心原则
shadcn/ui is not a component library—it's a collection of reusable components that you copy into your project. This gives you:
- Full ownership: Components live in your codebase, not node_modules
- Complete customization: Modify styling, behavior, and structure freely, including choosing between Radix UI or Base UI primitives
- No version lock-in: Update components selectively at your own pace
- Zero runtime overhead: No library bundle, just the code you need
shadcn/ui 不是组件库——它是一组可复制到你项目中的可复用组件。这能为你带来:
- 完全所有权:组件存放在你的代码库中,而非node_modules
- 完全自定义:可自由修改样式、行为和结构,包括在Radix UI或Base UI原语之间选择
- 无版本锁定:可根据自己的节奏选择性更新组件
- 零运行时开销:没有库捆绑包,只有你需要的代码
Component Discovery and Installation
组件发现与安装
1. Browse Available Components
1. 浏览可用组件
Use the shadcn MCP tools to explore the component catalog and Registry Directory:
- List all components: Use to see the complete catalog
list_components - Get component metadata: Use to understand props, dependencies, and usage
get_component_metadata - View component demos: Use to see implementation examples
get_component_demo
使用shadcn MCP工具探索组件目录和注册中心:
- 列出所有组件:使用查看完整组件目录
list_components - 获取组件元数据:使用了解组件的属性、依赖和用法
get_component_metadata - 查看组件演示:使用查看实现示例
get_component_demo
2. Component Installation
2. 组件安装
There are two approaches to adding components:
A. Direct Installation (Recommended)
bash
npx shadcn@latest add [component-name]This command:
- Downloads the component source code (adapting to your config: Radix vs Base UI)
- Installs required dependencies
- Places files in
components/ui/ - Updates your config
components.json
B. Manual Integration
- Use to retrieve the source code
get_component - Create the file in
components/ui/[component-name].tsx - Install peer dependencies manually
- Adjust imports if needed
添加组件有两种方式:
A. 直接安装(推荐)
bash
npx shadcn@latest add [component-name]该命令会:
- 下载组件源代码(适配你的配置:Radix UI或Base UI)
- 安装所需依赖
- 将文件放置在目录
components/ui/ - 更新你的配置
components.json
B. 手动集成
- 使用获取源代码
get_component - 在创建文件
components/ui/[component-name].tsx - 手动安装对等依赖
- 根据需要调整导入路径
3. Registry and Custom Registries
3. 注册中心与自定义注册中心
If working with a custom registry (defined in ) or exploring the Registry Directory:
components.json- Use to list available registries
get_project_registries - Use to see registry-specific components
list_items_in_registries - Use for detailed component information
view_items_in_registries - Use to find specific components
search_items_in_registries
如果使用自定义注册中心(在中定义)或探索注册中心目录:
components.json- 使用列出可用注册中心
get_project_registries - 使用查看注册中心专属组件
list_items_in_registries - 使用获取组件详细信息
view_items_in_registries - 使用查找特定组件
search_items_in_registries
Project Setup
项目设置
Initial Configuration
初始配置
For new projects, use the command to customize everything (style, fonts, component library):
createbash
npx shadcn@latest createFor existing projects, initialize configuration:
bash
npx shadcn@latest initThis creates with your configuration:
components.json- style: default, new-york (classic) OR choose new visual styles like Vega, Nova, Maia, Lyra, Mira
- baseColor: slate, gray, zinc, neutral, stone
- cssVariables: true/false for CSS variable usage
- tailwind config: paths to Tailwind files
- aliases: import path shortcuts
- rsc: Use React Server Components (yes/no)
- rtl: Enable RTL support (optional)
对于新项目,使用命令自定义所有配置(样式、字体、组件库):
createbash
npx shadcn@latest create对于现有项目,初始化配置:
bash
npx shadcn@latest init这会创建包含你的配置的文件:
components.json- style:default、new-york(经典)或选择Vega、Nova、Maia、Lyra、Mira等新视觉样式
- baseColor:slate、gray、zinc、neutral、stone
- cssVariables:是否启用CSS变量(true/false)
- tailwind config:Tailwind文件路径
- aliases:导入路径快捷方式
- rsc:是否使用React Server Components(是/否)
- rtl:启用RTL支持(可选)
Required Dependencies
必需依赖
shadcn/ui components require:
- React (18+)
- Tailwind CSS (3.0+)
- Primitives: Radix UI OR Base UI (depending on your choice)
- class-variance-authority (for variant styling)
- clsx and tailwind-merge (for class composition)
shadcn/ui组件需要:
- React (18+)
- Tailwind CSS (3.0+)
- 原语:Radix UI或Base UI(取决于你的选择)
- class-variance-authority(用于变体样式)
- clsx和tailwind-merge(用于类组合)
Component Architecture
组件架构
File Structure
文件结构
src/
├── components/
│ ├── ui/ # shadcn components
│ │ ├── button.tsx
│ │ ├── card.tsx
│ │ └── dialog.tsx
│ └── [custom]/ # your composed components
│ └── user-card.tsx
├── lib/
│ └── utils.ts # cn() utility
└── app/
└── page.tsxsrc/
├── components/
│ ├── ui/ # shadcn组件
│ │ ├── button.tsx
│ │ ├── card.tsx
│ │ └── dialog.tsx
│ └── [custom]/ # 你的组合组件
│ └── user-card.tsx
├── lib/
│ └── utils.ts # cn()工具函数
└── app/
└── page.tsxThe cn()
Utility
cn()cn()
工具函数
cn()All shadcn components use the helper for class merging:
cn()typescript
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}This allows you to:
- Override default styles without conflicts
- Conditionally apply classes
- Merge Tailwind classes intelligently
所有shadcn组件都使用助手进行类合并:
cn()typescript
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}这允许你:
- 无冲突地覆盖默认样式
- 有条件地应用类
- 智能合并Tailwind类
Customization Best Practices
自定义最佳实践
1. Theme Customization
1. 主题自定义
Edit your Tailwind config and CSS variables in :
app/globals.csscss
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
/* ... more variables */
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
/* ... dark mode overrides */
}
}在中编辑Tailwind配置和CSS变量:
app/globals.csscss
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
/* ... 更多变量 */
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
/* ... 深色模式覆盖 */
}
}2. Component Variants
2. 组件变体
Use (cva) for variant logic:
class-variance-authoritytypescript
import { cva } from "class-variance-authority"
const buttonVariants = cva(
"inline-flex items-center justify-center rounded-md",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground",
outline: "border border-input",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)使用(cva)处理变体逻辑:
class-variance-authoritytypescript
import { cva } from "class-variance-authority"
const buttonVariants = cva(
"inline-flex items-center justify-center rounded-md",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground",
outline: "border border-input",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)3. Extending Components
3. 扩展组件
Create wrapper components in (not ):
components/components/ui/typescript
// components/custom-button.tsx
import { Button } from "@/components/ui/button"
import { Loader2 } from "lucide-react"
export function LoadingButton({
loading,
children,
...props
}: ButtonProps & { loading?: boolean }) {
return (
<Button disabled={loading} {...props}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{children}
</Button>
)
}在目录(而非)创建包装组件:
components/components/ui/typescript
// components/custom-button.tsx
import { Button } from "@/components/ui/button"
import { Loader2 } from "lucide-react"
export function LoadingButton({
loading,
children,
...props
}: ButtonProps & { loading?: boolean }) {
return (
<Button disabled={loading} {...props}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{children}
</Button>
)
}Blocks and Complex Components
区块与复杂组件
shadcn/ui provides complete UI blocks (authentication forms, dashboards, etc.):
- List available blocks: Use with optional category filter
list_blocks - Get block source: Use with the block name
get_block - Install blocks: Many blocks include multiple component files
Blocks are organized by category:
- calendar: Calendar interfaces
- dashboard: Dashboard layouts
- login: Authentication flows
- sidebar: Navigation sidebars
- products: E-commerce components
shadcn/ui提供完整的UI区块(认证表单、仪表板等):
- 列出可用区块:使用并可选择类别筛选
list_blocks - 获取区块源代码:使用并传入区块名称
get_block - 安装区块:许多区块包含多个组件文件
区块按类别组织:
- calendar:日历界面
- dashboard:仪表板布局
- login:认证流程
- sidebar:导航侧边栏
- products:电商组件
Accessibility
可访问性
All shadcn/ui components are built on Radix UI primitives, ensuring:
- Keyboard navigation: Full keyboard support out of the box
- Screen reader support: Proper ARIA attributes
- Focus management: Logical focus flow
- Disabled states: Proper disabled and aria-disabled handling
When customizing, maintain accessibility:
- Keep ARIA attributes
- Preserve keyboard handlers
- Test with screen readers
- Maintain focus indicators
所有shadcn/ui组件都基于Radix UI原语构建,确保:
- 键盘导航:开箱即用的完整键盘支持
- 屏幕阅读器支持:正确的ARIA属性
- 焦点管理:合理的焦点流转
- 禁用状态:正确处理禁用和aria-disabled状态
自定义时,请保持可访问性:
- 保留ARIA属性
- 保留键盘处理器
- 使用屏幕阅读器测试
- 保持焦点指示器
Common Patterns
常见模式
Form Building
表单构建
typescript
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
// Use with react-hook-form for validation
import { useForm } from "react-hook-form"typescript
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
// 结合react-hook-form进行验证
import { useForm } from "react-hook-form"Dialog/Modal Patterns
对话框/模态框模式
typescript
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"typescript
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"Data Display
数据展示
typescript
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"typescript
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"Troubleshooting
故障排除
Import Errors
导入错误
- Check for correct alias configuration
components.json - Verify includes the
tsconfig.jsonpath alias:@json{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }
- 检查中的别名配置是否正确
components.json - 验证是否包含
tsconfig.json路径别名:@json{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }
Style Conflicts
样式冲突
- Ensure Tailwind CSS is properly configured
- Check that is imported in your root layout
globals.css - Verify CSS variable names match between components and theme
- 确保Tailwind CSS配置正确
- 检查是否在根布局中导入
globals.css - 验证组件和主题之间的CSS变量名称是否匹配
Missing Dependencies
缺失依赖
- Run component installation via CLI to auto-install deps
- Manually check for required Radix UI packages
package.json - Use to see dependency lists
get_component_metadata
- 通过CLI运行组件安装以自动安装依赖
- 手动检查中是否包含所需的Radix UI包
package.json - 使用查看依赖列表
get_component_metadata
Version Compatibility
版本兼容性
- shadcn/ui v4 requires React 18+ and Next.js 13+ (if using Next.js)
- Some components require specific Radix UI versions
- Check documentation for breaking changes between versions
- shadcn/ui v4需要React 18+和Next.js 13+(如果使用Next.js)
- 部分组件需要特定版本的Radix UI
- 查看文档了解版本间的破坏性变更
Validation and Quality
验证与质量
Before committing components:
- Type check: Run to verify TypeScript
tsc --noEmit - Lint: Run your linter to catch style issues
- Test accessibility: Use tools like axe DevTools
- Visual QA: Test in light and dark modes
- Responsive check: Verify behavior at different breakpoints
提交组件前:
- 类型检查:运行验证TypeScript
tsc --noEmit - 代码检查:运行代码检查工具捕捉样式问题
- 可访问性测试:使用axe DevTools等工具
- 视觉检查:在亮色和深色模式下测试
- 响应式检查:验证不同断点下的行为
Resources
资源
Refer to the following resource files for detailed guidance:
- - Step-by-step project initialization
resources/setup-guide.md - - Complete component reference
resources/component-catalog.md - - Theming and variant patterns
resources/customization-guide.md - - Upgrading from other UI libraries
resources/migration-guide.md
参考以下资源文件获取详细指导:
- - 分步项目初始化指南
resources/setup-guide.md - - 完整组件参考
resources/component-catalog.md - - 主题和变体模式
resources/customization-guide.md - - 从其他UI库迁移指南
resources/migration-guide.md
Examples
示例
See the directory for:
examples/- Complete component implementations
- Form patterns with validation
- Dashboard layouts
- Authentication flows
- Data table implementations
查看目录获取:
examples/- 完整组件实现
- 带验证的表单模式
- 仪表板布局
- 认证流程
- 数据表格实现