组件库怎样落地成设计系统:Headless UI、Mantine、shadcn 与样式边界
本文目录
后台越做越拥挤,通常不是再换一套组件库就能解决。标题、字段、按钮、弹窗和表格必须共享尺寸规则;组件把行为做好,产品仍要负责信息层级、文案和断点。本文用“新增内容弹窗”拆解这些边界。
四种层次,分别解决什么
| 层次 | 候选 | 你仍需负责 |
|---|---|---|
| 行为原语 | Headless UI | 视觉、间距、响应式和业务状态 |
| 成套组件 | Mantine、MUI、Vuetify | 主题令牌、表单流程、服务端权限 |
| 可维护的组件源码 | shadcn/ui | 合并上游修复、依赖升级、自己的变更 |
| 样式构建工具 | Tailwind CSS、Windi CSS | 语义结构、设计约束和可访问性 |
Headless UI 的 React 与 Vue 包有各自接口;MUI 面向 React,Vuetify 面向 Vue,不能因为都实现 Material Design 就直接互换。Mantine 的主题入口负责统一颜色和尺寸;不要让每个页面各建一套 Provider。shadcn/ui 允许团队维护自己的组件源码,依然有底层依赖,也依然需要升级。
Windi CSS 官方已经宣布不再新增功能,现有项目应评估维护成本;新项目先比较仍在维护的方案。维护公告说明的是维护方向,不是让已有系统立刻全量重写。
最小可用弹窗
在已有 React 工程安装 @headlessui/react 后,这个例子展示状态、标题和关闭行为;样式由项目自己提供。
import { useState } from 'react';
import { Dialog, DialogPanel, DialogTitle } from '@headlessui/react';
export function CreateDialog() {
const [open, setOpen] = useState(false);
return <>
<button onClick={() => setOpen(true)}>新建文档</button>
<Dialog open={open} onClose={setOpen} className="dialog-root">
<div className="dialog-backdrop" aria-hidden="true" />
<div className="dialog-position">
<DialogPanel className="dialog-panel">
<header><DialogTitle>新建文档</DialogTitle></header>
<form onSubmit={e => { e.preventDefault(); }}>
<label htmlFor="article-title">标题</label>
<input id="article-title" name="title" required maxLength={120} />
<footer>
<button type="button" onClick={() => setOpen(false)}>取消</button>
<button type="submit">创建草稿</button>
</footer>
</form>
</DialogPanel>
</div>
</Dialog>
</>;
}
提交处理只是占位;接入 API 时必须保留输入、显示服务端错误,成功后才关闭。还应处理提交中的重复点击、未保存内容和失效会话。
.dialog-root { position: relative; z-index: 1000; }
.dialog-backdrop { position: fixed; inset: 0; background: #10182788; }
.dialog-position { position: fixed; inset: 0; display: grid; place-items: center; padding: 12px; }
.dialog-panel {
box-sizing: border-box; width: min(560px, 100%);
max-height: calc(100dvh - 24px); overflow-y: auto;
overscroll-behavior: contain; border-radius: 16px; background: white; padding: 24px;
}
.dialog-panel input { box-sizing: border-box; width: 100%; min-height: 44px; font-size: 16px; }
.dialog-panel footer { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 12px; margin-top: 24px; }
预期:390px 屏幕左右至少留 12px;长表单在面板内部滚动;软键盘打开后仍有机会把底部按钮滚入视野。不要把宽度写死,再用全局 overflow:hidden 掩盖被裁掉的关闭按钮。
Tailwind 的动态类名陷阱
样式扫描器读取源码中的完整类名。类似 bg-${color}-500 的拼接可能没有对应产物,改成有限映射:
const tones = {
success: 'bg-emerald-100 text-emerald-900',
warning: 'bg-amber-100 text-amber-900',
};
const className = tones[state] ?? 'bg-slate-100 text-slate-900';
这也是内容平台不应让用户随便输入任意 CSS 类名的原因:可用状态应当有清楚的契约。第三方组件如果通过 Portal 挂到 body,.page .dialog 的规则不会自动覆盖它,必须用组件提供的弹层类名。
先固定规则,再覆盖页面
定义 4/8/12/16/24px 间距、统一圆角、边框色、主次按钮和错误状态。图标使用固定尺寸盒子,文字容器允许 min-width:0;收起导航时只隐藏文案,不压缩图标。表格保留内部横向滚动,页面外层不应整体变宽。
如何验收
用 320、390、768、1024 和桌面宽度查看同一套表单,另测 200% 缩放、长标题、空列表和网络错误。Tab 必须能进入弹窗、Esc 可关闭、关闭后焦点回到触发按钮。高对比度与减少动画偏好都要有可用表现。不要把“组件库自带可访问性”理解成组装完后无需再测。
官方资料
资源发现来源:25 项前端资源清单。本文示例与工程组织为独立编写。
留言提交后直接公开,请友善交流。