可复用输入组件经常出现在多个弹窗或设置面板中。如果每个组件都使用相同的 id,label、错误提示及辅助技术关联就可能指向错误元素。React useId 能生成适合组件实例的标识。本文讨论如何把它用于可复用的表单与信息面板,并说明它与列表 key 的区别。
1. 明确需要稳定标识的地方
HTML id 主要用于文档内唯一标识及元素关联。表单标签、帮助说明和错误信息是典型场景;不是所有节点都需要 id。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a2f13ad1991e0f598de03b9a82da17f67f901b33">
<label htmlFor={inputId}>显示名称</label>
<input id={inputId} name="displayName" />
</div>
2. 用 useId 生成组件实例标识
useId 应在组件顶层调用。用户复制两份字段组件时,每个实例都拥有独立标识,不需要全局自增变量。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/115366d0e61d87541a12f1b18745079ac292f282">
<label htmlFor={id}>{label}</label>
<input id={id} name={name} />
</div>
import { useId } from 'react';
function Field({ label, name }: { label: string; name: string }) {
const id = useId();
return <label htmlFor={id}>{label}<input id={id} name={name} /></label>;
}
3. 使用同一前缀派生关联 ID
一个字段的帮助文字和错误信息可从同一个 useId 派生,避免为每个关联节点单独建立状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/51652c9f07b7eaaab956f778f3008867ee1fe5ac">
<label htmlFor={`${id}-input`}>邮箱</label>
<input id={`${id}-input`} aria-describedby={`${id}-hint`} type="email" />
<p id={`${id}-hint`}>用于接收业务通知</p>
</div>
4. 条件错误信息需要正确关联
只在错误元素存在时将其 ID 加入 aria-describedby。aria-invalid 描述字段是否无效,不应把所有初始必填字段立即标记为错误。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c4d40e68ab325d4ea2cb67f1d4cf853bcc66f3f6">
<input id={inputId} aria-invalid={Boolean(error)} aria-describedby={error ? `${hintId} ${errorId}` : hintId} />
<p id={hintId}>请输入有效地址</p>
{error && <p id={errorId} role="alert">{error}</p>}
</div>
5. 为面板标题建立可访问名称
有意义的区域可以通过 aria-labelledby 指向可见标题。不要把每个普通 div 都升级成 landmark,否则页面导航会变得拥挤。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/690f209d77c4b377f85c70fd81fbe6842ab0b57f">
<section aria-labelledby={titleId}>
<h2 id={titleId}>通知设置</h2>
<p>管理消息接收偏好</p>
</section>
</div>
const titleId = useId();
6. 折叠控件使用 aria-controls
展开按钮通过 aria-expanded 反映实际状态,aria-controls 指向内容区域。使用原生 button 获得键盘交互,不需要模拟点击行为。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/d3fbbd526808b9378d86a88f1199eafe7e855613">
<button aria-expanded={expanded} aria-controls={panelId} onClick={() => setExpanded(v => !v)}>高级设置</button>
<section id={panelId} hidden={!expanded}>高级选项</section>
</div>
const panelId = useId();
const [expanded, setExpanded] = useState(false);
7. useId 不是列表 key
列表 key 应来自业务数据稳定身份。数组重排时,数据身份必须跟随记录,而不是跟随当前渲染位置。不要在 map 循环中调用 Hook。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4e61fb1b816f56cbfc14d974992112e3abe20a43">
<ul>{fields.map(field => <li key={field.id}><Field label={field.label} name={field.name} /></li>)}</ul>
</div>
8. 避免客户端随机值造成水合差异
随机 ID 在服务端与客户端可能不同。useId 为相同组件树提供适合水合的标识;多个独立根需要使用匹配的 identifierPrefix 配置。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/3d3bc9b70970e89a55d9d81e36e7cbadb5ce8a83">
<section><Field label="联系人" name="contact" /><Field label="部门" name="department" /></section>
</div>
服务器与客户端组件树仍需一致;useId 不会修复条件渲染结构不同造成的水合问题。
9. 测试应面向用户可访问名称
测试不必断言 React 生成的具体 ID 字符串。通过 label 查询输入框、通过 role 查询按钮,并验证描述文本和错误状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b3b4fcbc146dd1ed3ab4df1254f6c98582be52b3">
<Field label="用户名称" name="username" />
</div>
render(<Field label="用户名称" name="username" />);
expect(screen.getByLabelText('用户名称')).toBeInTheDocument();
10. 允许业务方显式传入标识
组件库可允许外部传入 id,用于与既有页面协议集成。但仍应无条件调用 useId,再选择传入值或生成值,避免违反 Hook 调用规则。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/216c279898f09d9e688dca51a15f5f74bdfcf32a">
<label htmlFor={resolvedId}>{label}</label>
<input id={resolvedId} name={name} />
</div>
const generatedId = useId();
const resolvedId = providedId ?? generatedId;
总结
useId 的重点是正确建立可访问的元素关联,而不是给每个节点增加随机标识。配合语义化 HTML、稳定业务 key 和面向用户的测试,可复用组件才能在多实例、服务端渲染和复杂表单中保持可靠。