文章目錄
- 什么是 Storybook?
- 使用場景舉例
- 快速上手教程(React 為例)
- 1. 安裝 Storybook
- 2. 創建一個 Story(組件故事)
- 3. 啟動 Storybook
- 常用功能
- 常見生態擴展
- 示例:用 Args 和 Controls 動態控制 Props
- 推薦資料
什么是 Storybook?
Storybook 是一個用于構建獨立組件 UI 的開發環境工具,適合 React、Vue、Angular 等現代前端框架。它允許你在不依賴項目業務的情況下,獨立開發、測試和文檔化 UI 組件。
官方文檔:https://storybook.js.org/
使用場景舉例
- 創建和預覽組件庫(如按鈕、表單等)
- 查看組件的不同狀態(如加載、禁用、成功)
- 為設計師、QA 或產品經理提供組件預覽
- 寫交互測試、可視化調試 UI 狀態
快速上手教程(React 為例)
1. 安裝 Storybook
在你的 React 項目中運行:
npx storybook@latest init
它會自動識別框架,安裝依賴,并創建 .storybook
配置目錄和示例 stories。
2. 創建一個 Story(組件故事)
假設你有一個 Button.tsx
組件,可以這樣寫 story:
// src/components/Button.tsx
import React from 'react';export const Button = ({ children, type = 'default', ...rest }) => (<button className={`btn btn-${type}`} {...rest}>{children}</button>
);
// src/components/Button.stories.tsx
import { Button } from './Button';export default {title: 'Components/Button',component: Button,
};export const Default = () => <Button>Default</Button>;
export const Primary = () => <Button type="primary">Primary</Button>;
export const Disabled = () => <Button disabled>Disabled</Button>;
3. 啟動 Storybook
npm run storybook
默認會在 http://localhost:6006
啟動一個獨立頁面,展示你定義的所有組件。
常用功能
功能 | 說明 |
---|---|
args | 控制組件的屬性(Props) |
controls | 自動生成 UI 控件修改 props |
docs | 自動生成組件文檔 |
actions | 捕捉事件(onClick 等) |
storybook/addon-interactions | 編寫交互測試 |
mdx 支持 | 寫 Markdown + JSX 格式文檔 |
常見生態擴展
@storybook/addon-essentials
(推薦插件集合)@storybook/addon-a11y
(無障礙輔助)storybook-addon-designs
(Figma/Zeplin 設計稿預覽)storybook-addon-themes
(多主題切換)
示例:用 Args 和 Controls 動態控制 Props
export const Playground = (args) => <Button {...args} />;
Playground.args = {children: 'Click me',type: 'primary',disabled: false,
};
這會生成 UI 控件讓你在頁面中動態調整按鈕的 props。
推薦資料
- 官網:https://storybook.js.org/
- 官方文檔:https://storybook.js.org/docs/react/get-started/introduction
- UI 測試集成(如 Playwright / Testing Library):官方有豐富支持