组件Controls
Form
@mox-hub/ui 组件 · Controls · canonical
form@mox-hub/uiControlscanonicalsrc/components/form.tsx变体演示form
Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| children* | React.ReactNode | React.ReactNode[] | — | — |
| watch* | UseFormWatch<TFieldValues> | — | — |
| getValues* | UseFormGetValues<TFieldValues> | — | — |
| getErrors* | UseFormGetErrors<TFieldValues> | — | — |
| getFieldState* | UseFormGetFieldState<TFieldValues> | — | — |
| setError* | UseFormSetError<TFieldValues> | — | — |
| clearErrors* | UseFormClearErrors<TFieldValues> | — | — |
| setValue* | UseFormSetValue<TFieldValues> | — | — |
| setValues* | UseFormSetValues<TFieldValues> | — | — |
| trigger* | UseFormTrigger<TFieldValues> | — | — |
| formState* | FormState<TFieldValues> | — | — |
| resetField* | UseFormResetField<TFieldValues> | — | — |
| reset* | UseFormReset<TFieldValues> | — | — |
| resetDefaultValues* | UseFormResetDefaultValues<TFieldValues> | — | — |
| handleSubmit* | UseFormHandleSubmit<TFieldValues, TTransformedValues> | — | — |
| unregister* | UseFormUnregister<TFieldValues> | — | — |
| control* | Control<TFieldValues, TContext, TTransformedValues> | — | — |
| register* | UseFormRegister<TFieldValues> | — | — |
| setFocus* | UseFormSetFocus<TFieldValues> | — | — |
| subscribe* | UseFormSubscribe<TFieldValues> | — | — |
源码
"use client"
import { mergeProps } from "@base-ui/react/merge-props"
import * as React from "react"
import {
Controller,
FormProvider,
type ControllerProps,
type FieldPath,
type FieldValues,
useFormContext,
} from "react-hook-form"
import { cn } from "../lib/utils"
import { Label } from "./label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
function FormField<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({ ...props }: ControllerProps<TFieldValues, TName>) {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
type FormItemContextValue = {
id: string
hasDescription: boolean
registerDescription: () => void
unregisterDescription: () => void
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId()
const [descriptionCount, setDescriptionCount] = React.useState(0)
const registerDescription = React.useCallback(() => {
setDescriptionCount((count) => count + 1)
}, [])
const unregisterDescription = React.useCallback(() => {
setDescriptionCount((count) => Math.max(0, count - 1))
}, [])
const contextValue = React.useMemo(
() => ({
id,
hasDescription: descriptionCount > 0,
registerDescription,
unregisterDescription,
}),
[id, descriptionCount, registerDescription, unregisterDescription]
)
return (
<FormItemContext.Provider value={contextValue}>
<div
data-slot="form-item"
// 审计 P2-34:与 ui/field 的 label→control→message 节奏对齐(gap-3)。
className={cn("flex flex-col gap-3", className)}
{...props}
/>
</FormItemContext.Provider>
)
}
function useFormField() {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
const id = itemContext.id
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
hasDescription: itemContext.hasDescription,
registerDescription: itemContext.registerDescription,
unregisterDescription: itemContext.unregisterDescription,
...fieldState,
}
}
function FormLabel({ className, ...props }: React.ComponentProps<typeof Label>) {
const { formItemId } = useFormField()
return (
<Label
data-slot="form-label"
className={cn(className)}
htmlFor={formItemId}
{...props}
/>
)
}
/**
* FormControl 把 id / aria-invalid / aria-describedby 合并到**唯一的子控件**上
* (2026-11-15 审计 P1-06)。此前这些属性挂在外层 div 上:`FormLabel` 的 htmlFor
* 指向 div(不可聚焦),`aria-invalid` 也不是 labelable 元素的有效属性。
*
* 用法保持不变:`<FormControl><Input /></FormControl>`。多子节点或无子节点时
* 回退为 div 容器(历史行为),避免破坏非标准用法。
*/
function FormControl({
className,
children,
...props
}: React.ComponentProps<"div">) {
const {
error,
formItemId,
formDescriptionId,
formMessageId,
hasDescription,
} = useFormField()
// P2-A2:FormDescription 可能不存在。只有在它真实挂载时才拼接 description id,
// 避免 aria-describedby 指向不存在的节点;错误消息同理只在有 error 时拼接。
const describedBy = [
hasDescription ? formDescriptionId : null,
error ? formMessageId : null,
]
.filter(Boolean)
.join(" ")
const controlProps = {
// 不再覆盖控件自身的 data-slot(Input 等仍保留 input/select 标记)
"data-form-control": "",
id: formItemId,
"aria-describedby": describedBy || undefined,
"aria-invalid": error ? true : undefined,
className: cn(className),
...props,
}
const child = React.Children.count(children) === 1 ? React.Children.only(children) : null
if (React.isValidElement(child)) {
return React.cloneElement(
child as React.ReactElement<Record<string, unknown>>,
mergeProps<"div">(controlProps, child.props as Record<string, unknown>),
)
}
return <div {...controlProps}>{children}</div>
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId, registerDescription, unregisterDescription } =
useFormField()
React.useEffect(() => {
registerDescription()
return () => unregisterDescription()
}, [registerDescription, unregisterDescription])
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function FormMessage({ className, children, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField()
const body = error ? String(error.message ?? "") : children
if (!body) {
return null
}
return (
<p
data-slot="form-message"
id={formMessageId}
role={error ? "alert" : undefined}
className={cn("text-sm font-normal text-destructive", className)}
{...props}
>
{body}
</p>
)
}
export {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
useFormField,
}
可访问性与 RTL
- 键盘:交互件保留
:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。 - RTL:间距、对齐与方向性图标使用逻辑属性 (
ms-*/text-start/rtl:-scale-x-100);通过ThemeProvider或I18nProvider的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。 - 文案:优先用组件
labels/translate/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
react-hook-form 集成,由 Form、FormField、FormItem、FormLabel、FormControl、FormMessage 组合;校验信息走 FormMessage。