React 教程
带类型的函数组件,每个组件一个文件,用标准的
value + onChange 模式受控——一切都按 React 本来的方式工作。
你将构建什么
一个小型联系表单——带标签的输入框、提交按钮、受控状态,以及真实的键盘和屏幕阅读器行为——先是不带样式的版本,再加上样式,大约 10 分钟完成。
开始之前
你需要 git、Node 22 或更高版本,以及 pnpm 10 或更高版本。任何 React 18+ 项目都可以——Next.js、Vite 或纯 React。
第 1 步——获取代码
git clone https://github.com/LilyDesignSystem/lily-design-system
cd lily-design-system/lily-design-system-react-headless
pnpm install
pnpm test # vitest + @testing-library/react
pnpm run storybook # browse all 571 components
组件是 components/ 中的扁平文件——
Button.tsx、TextInput.tsx——每个文件旁边都有它的测试、story 和文档。把你需要的文件复制到自己的应用中,或者把该仓库纳入自己的代码库并从中导入。
第 2 步——你的第一个组件
import Button from "lily-design-system-react-headless/components/Button";
export function SaveBar() {
return <Button onClick={save}>Save</Button>;
}
渲染为 <button class="button" type="button">。props:
type、disabled、pressed(渲染
aria-pressed)、label(覆盖
aria-label)、className,任何额外的属性都会展开到根元素上。
第 3 步——组合一个小表单
import { useState } from "react";
import Form from ".../components/Form";
import Field from ".../components/Field";
import TextInput from ".../components/TextInput";
import Button from ".../components/Button";
export function ContactForm() {
const [name, setName] = useState("");
return (
<Form label="Contact form" onSubmit={handleSubmit}>
<Field label="Full name" required>
<TextInput id="name" label="Full name" value={name} onChange={setName} required />
</Field>
<Button type="submit">Save</Button>
</Form>
);
}
Field 把可见的 label 作为自己的 prop,而不是嵌套一个标签组件——只需在
Field 上传入一次,TextInput 对应的
label 就会提供可访问名称。
2026-08-29 已验证:早期草稿在 Field 里嵌套了单独的 Label,结果渲染出两个标签(其中一个为空),因为 Field 已经会根据 label prop 渲染自己的标签——这是通过编译这段代码发现的。
联系表单组合路由
采用同样的模式,并经过真实的端到端测试和 axe 测试。
第 4 步——添加样式
以上所有内容渲染出来都是纯结构,随时可以套用你的样式。在你的样式表中为这些钩子设置样式——.button、
.text-input、.label、.field——或者通过 className 叠加 Tailwind 工具类,或者链接一个现成的主题:
<link rel="stylesheet" href="/themes/united-states-web-design-system.css" />
第 5 步——看看它的完整效果
Next.js 示例应用是完整目录的带样式演示版本,带有 Playwright 端到端测试和 axe-core 基线:
git clone https://github.com/LilyDesignSystem/lily-design-system
cd lily-design-system/lily-design-system-react-next-examples
pnpm install && pnpm run dev