ShadCN UI 模式 - 2025 年 11 月標準
何時使用
- 建構新的 UI 元件
- 重構現有元件以使用 ShadCN
- 實作含驗證的表單
- 建立模態框、對話框與疊層
- 確保無障礙合規性
為什麼選擇 ShadCN UI?
- 複製貼上,而非 npm - 完全擁有元件程式碼
- Radix UI 基礎元件 - 內建無障礙支援(WCAG 2.1 AA 等級)
- TailwindCSS 優先 - 完全自訂,無 CSS-in-JS
- TypeScript 原生 - 型別安全的 props 與變體
- Server Component 相容 - 可與 Next.js 15 App Router 搭配使用
核心原則
1. 元件安裝模式
# 依需求安裝個別元件
npx shadcn@latest add button
npx shadcn@latest add dialog
npx shadcn@latest add form
npx shadcn@latest add input
npx shadcn@latest add label
元件會被複製到 src/components/ui/ 目錄 — 你擁有程式碼的所有權。
2. 元件使用模式
Button 元件
import { Button } from "@/components/ui/button"
// ✅ 正確:使用語義化變體
<Button variant="default">儲存</Button>
<Button variant="destructive">刪除</Button>
<Button variant="outline">取消</Button>
<Button variant="ghost">跳過</Button>
<Button variant="link">了解更多</Button>
// ✅ 正確:使用尺寸變體
<Button size="default">中</Button>
<Button size="sm">小</Button>
<Button size="lg">大</Button>
<Button size="icon"><Icon /></Button>
// ❌ 錯誤:不使用 Button 元件而建立自訂按鈕
<button className="px-4 py-2 bg-blue-500">錯誤</button>
Dialog/Modal 元件
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
// ✅ 正確:使用正確的對話框結構(無障礙)
<Dialog>
<DialogTrigger asChild>
<Button>開啟設定</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>設定</DialogTitle>
<DialogDescription>
在此設定你的應用程式選項。
</DialogDescription>
</DialogHeader>
{/* 對話框內容 */}
</DialogContent>
</Dialog>
// ❌ 錯誤:省略 DialogHeader 或 DialogTitle(破壞螢幕閱讀器)
<DialogContent>
<h2>設定</h2> {/* 錯誤 - 應使用 DialogTitle */}
</DialogContent>
Form 元件(搭配 React Hook Form + Zod)
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
// ✅ 正確:先定義 Zod schema(驗證)
const formSchema = z.object({
email: z.string().email("無效的電子郵件地址"),
password: z.string().min(8, "密碼長度至少需要 8 個字元"),
})
function LoginForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
password: "",
},
})
async function onSubmit(values: z.infer<typeof formSchema>) {
// 型別安全的驗證資料
console.log(values)
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>電子郵件</FormLabel>
<FormControl>
<Input placeholder="[email protected]" {...field} />
</FormControl>
<FormDescription>
我們絕不會分享你的電子郵件。
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>密碼</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">登入</Button>
</form>
</Form>
)
}
// ❌ 錯誤:使用無驗證的非受控表單
<form>
<input name="email" /> {/* 無驗證 */}
</form>
3. Server vs Client Components
// ✅ 正確:對靜態對話框使用 Server Component
import { Dialog, DialogContent } from "@/components/ui/dialog"
export default function ServerDialog() {
// 不需要 'use client'
return <Dialog>...</Dialog>
}
// ✅ 正確:需要狀態時使用 Client Component
'use client'
import { useState } from 'react'
import { Dialog, DialogContent } from "@/components/ui/dialog"
export function ClientDialog() {
const [open, setOpen] = useState(false)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>...</DialogContent>
</Dialog>
)
}
4. 無障礙需求
焦點管理
// ✅ 正確:使用 asChild 搭配 DialogTrigger 以獲得正確焦點
<DialogTrigger asChild>
<Button>開啟</Button>
</DialogTrigger>
// ❌ 錯誤:手動觸發而未妥善處理焦點
<Button onClick={() => setOpen(true)}>開啟</Button>
鍵盤導航
// ✅ ShadCN 會自動處理:
// - ESC 關閉對話框
// - Tab 導航可聚焦元素
// - Enter/Space 啟用按鈕
// - 方向鍵導航選單
// ❌ 錯誤:沒有正當理由不要覆蓋預設鍵盤行為
螢幕閱讀器支援
// ✅ 正確:務必包含 DialogTitle(ARIA 必要)
<DialogHeader>
<DialogTitle>刪除專案</DialogTitle>
<DialogDescription>
此動作無法復原。
</DialogDescription>
</DialogHeader>
// ❌ 錯誤:不正確地使用視覺隱藏標題
<DialogTitle className="sr-only">刪除</DialogTitle>
// 僅在有清楚的視覺替代方案時才隱藏
5. 常用元件
| 元件 | 使用情境 | 關鍵 Props |
|---|---|---|
Button | 所有可點擊動作 | variant, size, asChild |
Dialog | 模態框、確認對話框 | open, onOpenChange |
Sheet | 側邊面板、抽屜 | side, open, onOpenChange |
Popover | 工具提示、選單 | open, onOpenChange |
Form | 所有表單 | form(來自 useForm) |
Input | 文字輸入 | type, placeholder |
Select | 下拉選單 | value, onValueChange |
Checkbox | 布林輸入 | checked, onCheckedChange |
RadioGroup | 單一選擇 | value, onValueChange |
Table | 資料表格 | table(來自 TanStack Table) |
Card | 內容容器 | CardHeader, CardContent, CardFooter |
Toast | 通知 | title, description, variant |
Command | 指令面板 | onSelect |
Tabs | 分頁導航 | value, onValueChange |
6. TailwindCSS 最佳實踐
// ✅ 正確:使用 Tailwind 工具類別
<Button className="w-full mt-4">提交</Button>
// ✅ 正確:使用 cn() 輔助函數處理條件類別
import { cn } from "@/lib/utils"
<Button className={cn(
"w-full",
isLoading && "opacity-50 cursor-not-allowed"
)}>
提交
</Button>
// ❌ 錯誤:使用內聯樣式
<Button style={{ width: '100%', marginTop: '16px' }}>提交</Button>
// ❌ 錯誤:為元件建立自訂 CSS 檔案
// styles.css
.my-button { width: 100%; }
7. 暗模式支援
// ✅ 正確:使用 Tailwind 暗模式類別
<div className="bg-white dark:bg-gray-900 text-black dark:text-white">
內容
</div>
// ✅ ShadCN 元件內建暗模式
<Button variant="default">
{/* 自動根據暗模式調整樣式 */}
</Button>
常見錯誤
❌ 遺漏 DialogTitle(無障礙違規)
// 錯誤
<DialogContent>
<h2>設定</h2>
<p>內容</p>
</DialogContent>
// 正確
<DialogContent>
<DialogHeader>
<DialogTitle>設定</DialogTitle>
</DialogHeader>
<p>內容</p>
</DialogContent>
❌ 未使用 Form 元件處理表單
// 錯誤 - 無驗證、使用者體驗差
<form>
<input name="email" />
<button type="submit">提交</button>
</form>
// 正確 - 有驗證、錯誤訊息、無障礙
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField name="email" ... />
</form>
</Form>
❌ 硬編碼顏色而非使用變體
// 錯誤
<Button className="bg-red-500 hover:bg-red-600">刪除</Button>
// 正確
<Button variant="destructive">刪除</Button>
❌ 未對觸發器使用 asChild
// 錯誤 - 建立不必要的巢狀按鈕
<DialogTrigger>
<Button>開啟</Button>
</DialogTrigger>
// 渲染:<button><button>開啟</button></button>(無效 HTML)
// 正確 - 將 props 合併到單一按鈕
<DialogTrigger asChild>
<Button>開啟</Button>
</DialogTrigger>
// 渲染:<button>開啟</button>
測試 ShadCN 元件
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Dialog, DialogTrigger, DialogContent } from '@/components/ui/dialog'
describe('Dialog', () => {
it('應在點擊觸發器時開啟', async () => {
const user = userEvent.setup()
render(
<Dialog>
<DialogTrigger asChild>
<button>開啟</button>
</DialogTrigger>
<DialogContent>
<div>對話框內容</div>
</DialogContent>
</Dialog>
)
// 對話框內容最初不應可見
expect(screen.queryByText('對話框內容')).not.toBeInTheDocument()
// 點擊觸發器
await user.click(screen.getByText('開啟'))
// 對話框內容現在應可見
expect(screen.getByText('對話框內容')).toBeInTheDocument()
})
it('應在按下 ESC 鍵時關閉', async () => {
const user = userEvent.setup()
render(
<Dialog defaultOpen>
<DialogContent>對話框內容</DialogContent>
</Dialog>
)
expect(screen.getByText('對話框內容')).toBeInTheDocument()
await user.keyboard('{Escape}')
expect(screen.queryByText('對話框內容')).not.toBeInTheDocument()
})
})
資源
- 官方文件:https://ui.shadcn.com
- Radix UI:https://www.radix-ui.com
- 範例:https://ui.shadcn.com/examples
- 主題:https://ui.shadcn.com/themes
2025 年 11 月備註
截至 2025 年 11 月,ShadCN UI 是 React 元件庫的行業標準。所有新的 Quetrex 應用程式必須使用 ShadCN UI,以確保一致性、無障礙性與可維護性。