实战

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 + NestJS 实战:用 AI 构建企业级 TypeScript 后端服务Claude Code 与 NestJS 框架深度协作实战:模块化架构设计(Module/Controller/Service/Provider)、让 Claude 生成符合 NestJS 惯例的 CRUD 模块、依赖注入系统的 AI 辅助使用、Guards 认证守卫(JWT/Role-based)、Interceptors 全局日志与请求变换、Pipes 数据验证(class-validator)、Exception Filters 统一异常处理、TypeORM 集成与数据库迁移、Swagger 文档自动生成,以及 NestJS 微服务(Microservices)架构入门。2026/3/21实战用 Claude Code 开发 Chrome 扩展:Manifest V3 + AI 助手从零到发布Claude Code 开发 Chrome 扩展完整实战:八步流程(项目规划/结构初始化/manifest.json/Service Worker/Popup+ContentScript/构建测试/MV3 坑点排查),含时效对比和三大关键经验。2026/3/14实战用 Claude Code 30 分钟搭建全栈 Todo 应用:从零到部署实战Claude Code 全栈实战教程:30 分钟搭建带认证的 Todo 应用(React+TypeScript+Express+SQLite+JWT),六步完整流程(规划架构/项目初始化/认证系统/CRUD API/前端实现/联调),附传统开发 vs Claude Code 时效对比与关键经验总结。2026/3/13实战Claude Code 命令行工具开发实战:用 AI 快速构建专业 CLI 工具Claude Code 辅助命令行工具(CLI)开发的完整实战指南:Python Click/Typer、Go Cobra、Rust Clap 技术栈选型、用 Claude Code 生成完整 CLI 项目结构(参数解析/子命令/全局选项)、交互式提示和彩色输出、配置文件管理、Shell 自动补全生成、跨平台打包(PyInstaller/goreleaser),以及发布到 PyPI/npm/Homebrew 的完整流程。2026/3/26