INFO · info-20251219-083
Storybook 快速指南 - UI 组件开发流程
[INFO] Storybook 快速指南 - UI 组件开发流程
- 时间: 2024-12-19
- 类型: 技术指南/工具手册
- 来源: 整理总结
- 置信度: 9/10
- 标签: #Storybook #UI #组件开发 #前端 #React
什么是 Storybook
用于构建 UI 组件的开源工具,提供独立环境来开发、测试和文档化组件。
核心优势
| 优势 | 说明 |
|---|---|
| 组件隔离开发 | 不依赖应用状态 |
| 可视化测试 | 直观查看不同状态 |
| 自动文档生成 | 基于代码自动生成 |
| 交互式调试 | 实时调整组件属性 |
| 团队协作 | 统一平台 |
快速安装
# 初始化 Storybook
npx storybook@latest init
# 启动开发服务器
npm run storybook
项目结构
project/
├── .storybook/
│ ├── main.js # 主配置
│ └── preview.js # 全局设置
├── src/
│ └── components/
│ └── Button/
│ ├── Button.jsx
│ ├── Button.css
│ └── Button.stories.js
核心概念
1. Stories(故事)
组件在特定状态下的渲染示例:
// Button.stories.js
import { Button } from './Button';
export default {
title: 'UI/Button',
component: Button,
tags: ['autodocs'],
};
export const Primary = {
args: {
variant: 'primary',
children: '主要按钮',
},
};
export const Disabled = {
args: {
disabled: true,
children: '禁用按钮',
},
};
2. Args(参数)
控制组件属性,支持动态调整:
export default {
argTypes: {
variant: {
control: 'select',
options: ['primary', 'secondary', 'danger'],
},
size: {
control: 'radio',
options: ['small', 'medium', 'large'],
},
disabled: {
control: 'boolean',
},
onClick: {
action: 'clicked',
},
},
};
3. Decorators(装饰器)
为故事添加包装器或上下文:
// 全局装饰器 (.storybook/preview.js)
export const decorators = [
(Story) => (
<div style={{ margin: '3em' }}>
<Story />
</div>
),
];
开发流程
1. 创建组件 → 2. 编写样式 → 3. 创建 Stories → 4. 添加交互测试
步骤详解
| 步骤 | 文件 | 内容 |
|---|---|---|
| 1 | Button.jsx | 组件实现 + PropTypes |
| 2 | Button.css | 样式定义 |
| 3 | Button.stories.js | 各状态故事 |
| 4 | 同上 | play 函数测试 |
交互测试示例
import { userEvent, within, expect } from '@storybook/test';
export const InteractionTest = {
args: { children: '点击测试' },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const button = canvas.getByRole('button');
await userEvent.click(button);
await expect(button).toHaveFocus();
},
};
参数控件类型
| 控件 | 用途 | 示例 |
|---|---|---|
text | 文本输入 | label |
select | 下拉选择 | variant |
radio | 单选按钮 | size |
boolean | 开关 | disabled |
color | 颜色选择器 | background |
range | 滑块 | opacity |
object | 对象编辑器 | data |
action | 动作记录 | onClick |
最佳实践
文件组织
components/Button/
├── index.js # 导出
├── Button.jsx # 实现
├── Button.css # 样式
├── Button.stories.js # 故事
└── Button.test.js # 测试
命名规范
export const Default = {}; // 默认状态
export const WithIcon = {}; // 带图标
export const Loading = {}; // 加载状态
export const Empty = {}; // 空状态
export const LongContent = {}; // 长内容
export const MobileView = {}; // 移动端视图
部署
# 构建静态版本
npm run build-storybook
# 部署到 Netlify
npx netlify deploy --dir=storybook-static --prod
# 部署到 Chromatic(视觉回归测试)
npx chromatic --project-token=<token>
CI/CD 集成
# .github/workflows/storybook.yml
jobs:
test:
steps:
- run: npm run build-storybook
- run: npm run test-storybook:ci
- run: npx chromatic --exit-zero-on-changes
核心价值
- 提高开发效率:隔离环境快速开发调试
- 改善代码质量:可视化测试发现问题
- 增强团队协作:统一的组件文档
- 确保一致性:建立设计系统标准
关联
- 相关: 前端开发工具链
- 相关: 组件驱动开发(CDD)
- 待验证: 在实际项目中的应用效果