用故事书构建设计系统并进行反应
首先使用npx storybook init在React项目中安装并配置Storybook,运行npm run storybook启动本地开发服务器;2. 按功能或类型组织组件文件结构,在每个组件目录下创建对应的.stories.js文件定义不同状态的展示;3. 利用Storybook的Args和Controls系统实现属性动态调整,方便测试各种交互状态;4. 使用MDX文件编写包含设计规范、可访问性说明等内容的富文本文档,并通过配置支持MDX加载;5. 通过theme.js定义设计令牌并在preview.js中使用ThemeProvider全局注入主题样式;6. 集成Jest、React Testing Library进行单元测试,使用Chromatic进行视觉回归测试,并通过@storybook/addon-a11y检查可访问性问题。最终建立一个支持独立开发、可视化文档、自动化测试且促进设计与开发协作的可扩展设计系统,该系统通过逐步迭代组件实现跨团队高效复用,成为提升UI一致性和开发效率的必要工具。
Building a design system with Storybook and React is a powerful way to create consistent, reusable UI components that scale across teams and products. Storybook provides an isolated development environment for UI components, making it easier to build, test, and document them in isolation—without relying on the full app. When paired with React, this combo becomes a go-to setup for modern design systems.

Here’s how to approach it effectively.
1. Set Up Storybook with React
Start by adding Storybook to your React project. If you're using Create React App or a standard React setup, the easiest way is using the automated CLI:

npx storybook init
This command installs Storybook, adds the necessary configuration files, and sets up example stories. Once done, run:
npm run storybook
This starts the Storybook development server, usually at http://localhost:6006
, where you can view your components in real time.

Tip: The init command works well with most React setups, including Vite and Next.js. If you're using a custom webpack config, you might need to adjust
.storybook/main.js
accordingly.
2. Structure Your Components and Stories
A well-organized file structure is key to maintainability. Group components logically—typically by feature or type (e.g., atoms
, molecules
, organisms
), or by category like Button
, Form
, Navigation
.
Example structure:
src/ ├── components/ │ ├── Button/ │ │ ├── Button.jsx │ │ ├── Button.stories.js │ │ └── Button.module.css │ ├── Input/ │ │ ├── Input.jsx │ │ └── Input.stories.js ├── styles/ │ └── theme.js
In each .stories.js
file, define how the component should be rendered in different states:
// Button.stories.js import { Button } from './Button'; export default { title: 'Components/Button', component: Button, argTypes: { variant: { control: 'select', options: ['primary', 'secondary'] }, }, }; export const Primary = { args: { label: 'Click me', variant: 'primary', }, }; export const Disabled = { args: { label: 'Disabled', disabled: true, }, };
This creates interactive controls (like dropdowns for props) and lets designers and developers explore variations visually.
3. Use Args and Controls for Dynamic Testing
Storybook’s Args system allows you to change component inputs on the fly. Combined with Controls, users can tweak props directly in the UI—great for testing edge cases and showcasing flexibility.
Example:
argTypes: { size: { control: 'radio', options: ['small', 'medium', 'large'] }, onClick: { action: 'clicked' }, // logs clicks }
This means QA, PMs, or designers can interact with the button and see how it behaves when clicked or resized—without touching code.
Pro tip: Use
controls: { exclude: ['id', 'className'] }
to hide internal or non-visual props from the controls panel.
4. Document with MDX and Add Design Guidelines
Go beyond code examples. Use MDX (Markdown JSX) to write rich documentation that includes design tokens, usage guidelines, accessibility notes, and even Figma links.
Create a Button.stories.mdx
file:
import { Meta, Story, Canvas } from '@storybook/blocks'; import * as ButtonStories from './Button.stories.js'; <Meta title="Components/Button" component={Button} /> # Button Use buttons to trigger actions. Prefer primary buttons for main actions, secondary for alternatives. <Canvas> <Story of={ButtonStories.Primary} /> </Canvas> ## Accessibility Always include descriptive labels. Avoid icon-only buttons unless properly labeled with `aria-label`.
Then configure Storybook to load MDX files by updating .storybook/main.js
:
module.exports = { stories: ['../src/**/*.stories.@(js|jsx|ts|tsx|mdx)'], // ... };
Now your design system becomes a living style guide.
5. Integrate Design Tokens and Theming
Share visual styles (colors, typography, spacing) via a theme object, often using styled-components
, emotion
, or CSS-in-JS.
Example theme:
// theme.js export const theme = { colors: { primary: '#007bff', secondary: '#6c757d', }, spacing: (factor) => `${0.5 * factor}rem`, typography: { heading: 'bold 1.5rem system-ui', }, };
Wrap your stories with a decorator to apply the theme globally in .storybook/preview.js
:
import { ThemeProvider } from 'styled-components'; import { theme } from '../src/styles/theme'; export const decorators = [ (Story) => ( <ThemeProvider theme={theme}> <Story /> </ThemeProvider> ), ];
Now all components render with consistent styling.
6. Add Testing and Automation
A robust design system needs tests. Combine:
- Jest React Testing Library for unit and behavior tests.
- Chromatic (a Storybook add-on) for visual regression testing.
Install Chromatic:
npx chromatic --project-token=<your-token>
It runs in CI and compares every story against previous versions, catching unintended visual changes.
Also consider adding a11y addon to catch accessibility issues:
npm install @storybook/addon-a11y
Then enable it in .storybook/main.js
:
addons: ['@storybook/addon-a11y'];
Now you’ll see an Accessibility tab in the UI with automated checks.
Final Thoughts
Building a design system with Storybook and React isn’t just about components—it’s about creating a shared language between design and development. With the right setup, you get:
- Isolated component development
- Interactive documentation
- Visual testing and consistency
- Collaboration-friendly interfaces
Start small (buttons, inputs), enforce consistency early, and grow iteratively. Over time, your design system becomes a force multiplier for product teams.
Basically, if you're using React and care about UI quality, Storybook isn’t optional—it’s essential.
以上是用故事书构建设计系统并进行反应的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undress AI Tool
免费脱衣服图片

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

TypeScript的高级条件类型通过TextendsU?X:Y语法实现类型间的逻辑判断,其核心能力体现在分布式条件类型、infer类型推断和复杂类型工具的构建。1.条件类型在裸类型参数上具有分布性,能自动对联合类型拆分处理,如ToArray得到string[]|number[]。2.利用分布性可构建过滤与提取工具:Exclude通过TextendsU?never:T排除类型,Extract通过TextendsU?T:never提取共性,NonNullable过滤null/undefined。3

Microfrontendssolvescalingchallengesinlargeteamsbyenablingindependentdevelopmentanddeployment.1)Chooseanintegrationstrategy:useModuleFederationinWebpack5forruntimeloadingandtrueindependence,build-timeintegrationforsimplesetups,oriframes/webcomponents

varisfunction-scoped,canbereassigned,hoistedwithundefined,andattachedtotheglobalwindowobject;2.letandconstareblock-scoped,withletallowingreassignmentandconstnotallowingit,thoughconstobjectscanhavemutableproperties;3.letandconstarehoistedbutnotinitial

本文深入探讨了如何为“双巧克力”(Double-Choco)谜题游戏自动生成可解谜题。我们将介绍一种高效的数据结构——基于2D网格的单元格对象,该对象包含边界信息、颜色和状态。在此基础上,我们将详细阐述一种递归的块识别算法(类似于深度优先搜索),以及如何将其整合到迭代式谜题生成流程中,以确保生成的谜题满足游戏规则,并具备可解性。文章将提供示例代码,并讨论生成过程中的关键考量与优化策略。

使用JavaScript从DOM元素中删除CSS类最常用且推荐的方法是通过classList属性的remove()方法。1.使用element.classList.remove('className')可安全删除单个或多个类,即使类不存在也不会报错;2.替代方法是直接操作className属性并通过字符串替换移除类,但易因正则匹配不准确或空格处理不当引发问题,因此不推荐;3.可通过element.classList.contains()先判断类是否存在再删除,但通常非必需;4.classList

JavaScript的class语法是原型继承的语法糖,1.class定义的类本质是函数,方法添加到原型上;2.实例通过原型链查找方法;3.static方法属于类本身;4.extends通过原型链实现继承,底层仍使用prototype机制,class未改变JavaScript原型继承的本质。

本文旨在解决在Vercel上部署单页应用(SPA)时,深层URL刷新或直接访问导致页面资源加载失败的问题。核心在于理解Vercel的路由重写机制与浏览器解析相对路径的差异。通过配置vercel.json实现所有路径重定向至index.html,并修正HTML中静态资源的引用方式,将相对路径改为绝对路径,确保应用在任何URL下都能正确加载所有资源。

JavaScript的数组方法map、filter和reduce用于编写清晰、函数式的代码。1.map用于转换数组中的每个元素并返回新数组,如将摄氏温度转为华氏温度;2.filter用于根据条件筛选元素并返回符合条件的新数组,如获取偶数或活跃用户;3.reduce用于累积结果,如求和或统计频次,需提供初始值并返回累加器;三者均不修改原数组,可链式调用,适用于数据处理与转换,提升代码可读性与功能性。
