Skip to content

设计系统与组件库工程 ​

组件库不是把按钮、弹窗、表格做一遍。组件库的目标是让产品在变化中保持一致。

一句话先记住:设计系统 = design token + 基础组件 + 组合组件 + 文档 + 约束。


一、组件库分层 ​

text
tokens
  -> primitive components
  -> composite components
  -> product patterns

例子:

text
tokens:
  color, spacing, radius, typography, shadow

primitive:
  Button, Input, Dialog, Tooltip, Tabs

composite:
  SearchForm, DataTable, UserPicker

patterns:
  CRUD page, Settings page, Empty state, Error state

不要把所有东西都叫组件。越底层越通用,越上层越业务化。


二、Design Tokens ​

Token 是设计系统的变量层:

css
:root {
  --color-bg: #ffffff;
  --color-fg: #111827;
  --color-primary: #2563eb;
  --color-danger: #dc2626;

  --space-1: 4px;
  --space-2: 8px;
  --space-3: 12px;
  --space-4: 16px;

  --radius-sm: 4px;
  --radius-md: 6px;
  --radius-lg: 8px;
}

[data-theme='dark'] {
  --color-bg: #111827;
  --color-fg: #f9fafb;
}

组件只读 token:

css
.button {
  border-radius: var(--radius-md);
  padding: var(--space-2) var(--space-3);
  background: var(--color-primary);
}

不要在组件里写散值:

css
/* 坏 */
.button {
  border-radius: 7px;
  padding: 9px 15px;
  background: #1f6feb;
}

散值越多,系统越快失控。


三、组件 API 设计 ​

按钮最小 API:

tsx
type ButtonProps = {
  variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
  size?: 'sm' | 'md' | 'lg';
  loading?: boolean;
  disabled?: boolean;
} & React.ButtonHTMLAttributes<HTMLButtonElement>;

实现:

tsx
import { cva } from 'class-variance-authority';

const buttonClass = cva('inline-flex items-center justify-center font-medium', {
  variants: {
    variant: {
      primary: 'bg-blue-600 text-white',
      secondary: 'bg-gray-100 text-gray-900',
      danger: 'bg-red-600 text-white',
      ghost: 'bg-transparent text-gray-900',
    },
    size: {
      sm: 'h-8 px-3 text-sm',
      md: 'h-10 px-4 text-sm',
      lg: 'h-11 px-5 text-base',
    },
  },
  defaultVariants: {
    variant: 'primary',
    size: 'md',
  },
});

export function Button({ variant, size, loading, disabled, children, ...props }: ButtonProps) {
  return (
    <button
      className={buttonClass({ variant, size })}
      disabled={disabled || loading}
      {...props}
    >
      {loading ? 'Loading...' : children}
    </button>
  );
}

API 要收敛。不要这样:

tsx
<Button blue big rounded shadow bold center />

这不是 API,这是把 CSS props 泄漏给使用者。


四、组合组件 ​

基础组件不懂业务:

tsx
<Dialog>
  <DialogTitle />
  <DialogContent />
  <DialogFooter />
</Dialog>

业务组合组件可以懂业务:

tsx
export function DeleteUserDialog({ userId, open, onOpenChange }: Props) {
  const mutation = useDeleteUser();

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogTitle>Delete user</DialogTitle>
      <DialogContent>This action cannot be undone.</DialogContent>
      <DialogFooter>
        <Button variant="secondary" onClick={() => onOpenChange(false)}>Cancel</Button>
        <Button
          variant="danger"
          loading={mutation.isPending}
          onClick={() => mutation.mutate(userId)}
        >
          Delete
        </Button>
      </DialogFooter>
    </Dialog>
  );
}

别把业务逻辑塞进基础 Dialog。基础组件一旦懂业务,就复用不了。


五、Storybook 的位置 ​

Storybook 解决三件事:

text
组件文档
视觉回归
交互用例沉淀

一个 Button story:

tsx
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './button';

const meta = {
  component: Button,
  args: {
    children: 'Save',
    variant: 'primary',
    size: 'md',
  },
} satisfies Meta<typeof Button>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Primary: Story = {};

export const Danger: Story = {
  args: {
    variant: 'danger',
    children: 'Delete',
  },
};

export const Loading: Story = {
  args: {
    loading: true,
  },
};

没有 Story 的组件库,很快会变成"只能靠问作者怎么用"。


六、组件状态要完整 ​

每个基础组件至少考虑:

text
default
hover
active
focus-visible
disabled
loading
error
empty
readonly
dark mode
mobile

表单组件还要考虑:

text
label
description
required
error message
aria-describedby

示例:

tsx
type FieldProps = {
  label: string;
  error?: string;
  description?: string;
  children: React.ReactElement;
};

export function Field({ label, error, description, children }: FieldProps) {
  const id = useId();
  const descriptionId = `${id}-description`;
  const errorId = `${id}-error`;

  return (
    <div className="space-y-1">
      <label htmlFor={id}>{label}</label>
      {React.cloneElement(children, {
        id,
        'aria-describedby': error ? errorId : description ? descriptionId : undefined,
        'aria-invalid': error ? true : undefined,
      })}
      {description && !error ? <p id={descriptionId}>{description}</p> : null}
      {error ? <p id={errorId} role="alert">{error}</p> : null}
    </div>
  );
}

七、不要过早造轮子 ​

基础无障碍组件建议用成熟库:

text
Radix UI       React,无样式,a11y 强
React Aria     Adobe,底层能力强
Headless UI    Tailwind 团队,简单
Ark UI         多框架 headless
Kobalte        SolidJS

自己写 Dialog / Select / Combobox 很容易漏:

  • focus trap
  • keyboard navigation
  • screen reader label
  • scroll lock
  • portal stacking
  • nested overlay

样式可以自己做,交互语义尽量别手写。


八、版本与破坏性变更 ​

组件库要有 changelog:

text
patch:修 bug,不改 API
minor:加能力,向后兼容
major:删 API / 改默认行为

破坏性变更要给迁移方式:

md
## Button `tone` renamed to `variant`

Before:
<Button tone="danger" />

After:
<Button variant="danger" />

公司内部组件库也需要版本纪律。否则所有业务项目都会被隐式破坏。


九、组件库目录 ​

text
packages/ui/
  src/
    tokens/
      theme.css
    button/
      button.tsx
      button.stories.tsx
      button.test.tsx
      index.ts
    dialog/
      dialog.tsx
      dialog.stories.tsx
      dialog.test.tsx
      index.ts
    index.ts
  package.json

导出要稳定:

ts
export { Button } from './button';
export type { ButtonProps } from './button';

不要让业务方 import 内部文件:

ts
// 不要
import { Button } from '@acme/ui/src/button/button';

十、检查清单 ​

  • [ ] token 是否覆盖颜色、间距、圆角、字体、阴影
  • [ ] 组件 API 是否收敛为 variant / size / state
  • [ ] 是否有 Storybook 用例
  • [ ] 是否覆盖 loading / disabled / error / empty
  • [ ] 是否满足键盘和读屏器可用
  • [ ] 复杂交互是否基于 headless 库
  • [ ] 是否有 changelog 和破坏性变更策略
  • [ ] 是否禁止业务项目 import 内部路径

十一、心智模型 ​

text
Design Tokens 决定视觉语言
Primitive Components 决定交互语义
Composite Components 决定复用效率
Storybook 决定可发现性
版本纪律决定能不能长期维护

组件库做得好,业务代码会变短。组件库做得差,业务代码会被迫绕开它。

下一篇 46 讲复杂表格、筛选与批量操作。