Claude Code 特别擅长 React 开发——它理解组件设计原则、Hooks 模式、TypeScript 类型,能从自然语言需求直接生成可用的组件代码。本文展示完整的工作流程。
基础模板:让 Claude 生成标准组件
Create a React component: UserAvatar
Props:
- src?: string (image URL, optional)
- name: string (user's display name)
- size?: 'sm' | 'md' | 'lg' (default: 'md')
- online?: boolean (show green dot indicator)
Behavior:
- Show image if src provided, else show initials from name
- Initials: first letter of first and last word
- Size mapping: sm=32px, md=40px, lg=56px
- Online indicator: small green dot bottom-right
Tech: TypeScript, Tailwind CSS
File: src/components/UserAvatar.tsx
工作流 1:从设计规范生成组件
Create a NotificationBadge component based on these specs:
Design:
- Small red circle with white number
- Position: top-right corner of parent element
- Show nothing if count is 0
- Show '99+' if count > 99
- Animate in with scale transition on mount
Usage:
<NotificationBadge count={unreadCount}>
<BellIcon />
</NotificationBadge>
TypeScript + Tailwind, save to src/components/ui/NotificationBadge.tsx
工作流 2:带状态管理的复杂组件
Create a SearchableSelect component:
Features:
- Dropdown with search input
- Async options loading (pass loadOptions async function as prop)
- Loading spinner while fetching
- Debounce search input (300ms)
- Keyboard navigation (arrow keys, enter, escape)
- Multi-select support (optional)
- Clear selection button
Types:
interface Option { value: string; label: string; disabled?: boolean }
interface SearchableSelectProps {
loadOptions: (query: string) => Promise<Option[]>
value?: Option | Option[]
onChange: (value: Option | Option[]) => void
multi?: boolean
placeholder?: string
}
Use React hooks only (no external state lib)
Style with Tailwind CSS
工作流 3:表单组件 + 验证
Create a UserProfileForm component:
Fields: name (required), email (required, valid format),
bio (optional, max 200 chars), avatar upload
Requirements:
- Use React Hook Form + Zod validation
- Show inline error messages
- Avatar preview before upload
- Dirty state tracking (show 'Unsaved changes' warning)
- Submit calls async onSubmit prop, shows loading state
- Success/error toast notification after submit
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
工作流 4:数据展示表格
Create a DataTable<T> generic component:
Features:
- Column definition with sort, filter, custom render
- Client-side sort (click header)
- Pagination: 10/25/50 per page selector
- Row selection (checkbox, single/multi)
- Column visibility toggle
- CSV export button
- Empty state and loading skeleton
Based on TanStack Table v8 (@tanstack/react-table)
Style: Tailwind CSS + shadcn/ui Table
Example usage:
<DataTable
data={users}
columns={[{key:'name',header:'Name',sortable:true},...]}
onRowSelect={setSelected}
/>
工作流 5:为组件写测试
Write React Testing Library tests for UserAvatar component.
Test cases:
1. Renders image when src is provided
2. Shows initials when no src (e.g. 'John Doe' -> 'JD')
3. Single word name shows first letter only ('Alice' -> 'A')
4. Online indicator visible when online=true
5. No online indicator when online=false or undefined
6. Size variants apply correct CSS classes
7. Image loads with correct alt text
Use @testing-library/react, @testing-library/jest-dom
Mock: vi.fn() for Vitest
File: src/components/__tests__/UserAvatar.test.tsx
工作流 6:重构已有组件
Refactor this legacy React component:
[粘贴现有组件代码]
Goals:
1. Convert class component to functional + hooks
2. Add TypeScript types (no 'any')
3. Extract logic into custom hooks
4. Memoize expensive computations with useMemo/useCallback
5. Fix any React anti-patterns
Don't change the external API (props/behavior must stay the same)
工作流 7:生成 Storybook Stories
Generate Storybook stories for UserAvatar component.
Include these stories:
- Default: with image
- WithInitials: no image, show initials
- Online: with green indicator
- AllSizes: show sm, md, lg variants side by side
- LongName: edge case with long display name
Use Storybook 7+ CSF3 format with TypeScript.
Add argTypes for interactive Storybook controls.
File: src/components/UserAvatar.stories.tsx
推荐 CLAUDE.md 配置(React 项目)
markdown
## React 规范
- 函数组件 + Hooks,不用 class 组件
- Props 必须有 TypeScript interface
- 复杂逻辑抽成自定义 Hook(src/hooks/)
- 组件文件:PascalCase.tsx
- 每个组件必须有对应测试文件
- 样式:Tailwind CSS,不写内联 style
## 测试规范
- 框架:Vitest + React Testing Library
- 覆盖率目标:>80%
- 命名:Component.test.tsx来源:Anthropic 官方文档 + React 官方文档