实战

Claude Code 写 React 组件:从需求描述到单元测试的完整工作流

Claude Code 开发 React 组件完整工作流:需求转组件设计、TypeScript Props 定义、Hooks 实现、Tailwind 样式、React Testing Library 测试、Storybook 文档,以及复杂组件(表格/表单/弹窗)的高效开发模式。

2026/3/154分钟 阅读ClaudeEagle

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 官方文档

相关文章推荐

实战Claude Code + Next.js 15 全栈开发实战:从零搭建现代 Web 应用Claude Code 与 Next.js 15 结合开发完整教程:App Router 结构生成、Server/Client Components、API Routes、Prisma 数据库集成、Tailwind CSS UI、NextAuth 认证、Vercel 部署,以及 Claude Code 加速 Next.js 开发的 10 个核心工作流。2026/3/15实战Claude Code + Tailwind CSS:10 分钟从零搭建现代 UI 组件库用 Claude Code 快速构建 Tailwind CSS UI 组件完整教程:响应式布局、组件库生成、深色模式、动画效果、与 React/Vue 集成,以及通过对话式迭代快速调整设计稿的工作流。2026/3/15实战Claude Code React Server Components 实战:Next.js 15 RSC 开发完全指南(2026)Claude Code 辅助 React Server Components(RSC)开发完整指南:服务端 vs 客户端组件选择原则、服务端直连数据库的页面写法、客户端交互组件 + Server Action 乐观更新、Suspense 流式渲染(主内容快速显示+慢数据不阻塞)、三类常见 RSC 错误诊断(useState/Event Handlers/Hydration),适配 Next.js 15。2026/3/30实战Claude Code Playwright E2E 测试实战:AI 辅助编写端到端测试完全指南(2026)Claude Code 辅助 Playwright E2E 测试完整指南:从用户故事直接生成 Page Object Model 测试、修复 Flaky Tests(硬等待→等待元素/API请求)、API Mock 联合测试、GitHub Actions 并行3分片CI加速,附截图生成测试/批量边界条件/Core Web Vitals 测试 Prompt 模板。2026/3/29实战Claude Code Playwright E2E 测试实战:AI 辅助编写端到端测试完全指南(2026)Claude Code 辅助 Playwright E2E 测试完整指南:从用户故事直接生成 Page Object Model 测试、修复 Flaky Tests(硬等待→等待元素/网络请求)、API Mock + E2E 联合测试、GitHub Actions CI/CD 并行分片(3 shard 加速)、截图视频上传,附从截图生成测试/边界条件批量生成/Core Web Vitals 测试 Prompt 模板。2026/3/29实战Claude Code Prisma ORM 实战完全指南:AI 辅助现代 TypeScript 数据库开发(2026)Claude Code 辅助 Prisma ORM 开发的完整实战指南:从需求直接生成 Prisma Schema(多表关系/@relation/@@index/枚举)、复杂查询生成(include/select/cursor分页)、Prisma 事务处理(原子操作/库存扣减)、安全的数据库 Migration 策略(生产环境不停机迁移)、N+1 查询问题排查与优化,覆盖 PostgreSQL/MySQL/SQLite 三种数据库。2026/3/27