组织字段、标签和校验提示,收集表单数据。
基础用法
为控件设置 name,通过提交事件中的 FormData 读取值。FormField required 配合输入类型进行原生校验,错误显示在对应字段下方。
import { Button, Flex, Form, FormField, Input, Select, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';
export function FormBasic() {
const [result, setResult] = useState('');
return (
<Form
onSubmit={(event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
setResult(`${data.get('name')} · ${data.get('email')} · ${data.get('team')}`);
}}
onReset={() => setResult('')}
>
<FormField label="姓名" required>
<Input name="name" placeholder="你的姓名" />
</FormField>
<FormField label="工作邮箱" required help="用于接收项目通知">
<Input name="email" type="email" placeholder="hello@example.com" />
</FormField>
<FormField label="所属团队" required>
<Select
name="team"
options={[
{ value: 'design', label: '设计团队' },
{ value: 'engineering', label: '工程团队' },
]}
/>
</FormField>
<FormField>
<Flex gap="sm" wrap>
<Button type="submit" variant="solid">
提交
</Button>
<Button type="reset" variant="outline">
重置
</Button>
</Flex>
</FormField>
{result && (
<FormField>
<Text role="status" tone="muted">
已提交:{result}
</Text>
</FormField>
)}
</Form>
);
}
示例
标签宽度
水平布局和设置布局的标签列默认宽度为 112px。通过 Form.labelWidth 统一调整,或通过 FormField.labelWidth 单独覆盖;数字按像素处理,字符串可以使用 20%、12rem 或 clamp() 等 CSS 值。长标签在指定宽度内换行。水平和设置布局在窄容器内自动上下排列。
import { Form, FormField, Input } from '@ifhover/leaf-ui';
export function FormLabelWidth() {
return (
<Form labelWidth={140}>
<FormField label="姓名">
<Input name="name" />
</FormField>
<FormField label="工作邮箱">
<Input name="email" />
</FormField>
<FormField label="备注" labelWidth={80}>
<Input name="notes" />
</FormField>
</Form>
);
}
通过 CSS 设置标签宽度
项目使用 postcss-pxtorem 等构建工具时,可将宽度写在样式表中,让 CSS 构建流程统一转换单位;也可以直接使用 rem。下面通过 style 将标签宽度关联到应用的 CSS 变量。
.account-form {
--app-form-label-width: 140px;
}
import { Form, FormField, Input, type LeafThemeStyle } from '@ifhover/leaf-ui';
import './account-form.css';
const formStyle = {
'--leaf-form-label-width': 'var(--app-form-label-width)',
} satisfies LeafThemeStyle;
export function AccountForm() {
return (
<Form className="account-form" style={formStyle}>
<FormField label="账号名称">
<Input name="account" />
</FormField>
</Form>
);
}
140px 是否转换以及转换比例由应用的构建配置决定,需确保该样式表与自定义属性声明纳入转换范围。数字 labelWidth 会生成内联像素值,通常不会经过 PostCSS 转换;字符串值会原样作为 CSS 宽度传递。当前 Form 默认也会生成内联宽度,因此仅在同一个 Form 的 CSS 类中声明 --leaf-form-label-width 不能覆盖默认值;上例使用 style 显式连接 CSS 变量,不需要 !important。
需要全应用统一时,可将 --app-form-label-width 定义在应用根节点,并通过 ConfigProvider components={{ Form: { style: formStyle } }} 配置一次。style 整体替换、不合并;单个 Form 另传 style 时,需要保留该变量关联。FormField.labelWidth 或字段自身的同名 CSS 变量仍可覆盖该字段。
设置布局
layout="settings" 将标签与 description 放在控件左侧,左侧宽度读取 labelWidth,右侧控件默认占用扣除间隙后的剩余宽度并左对齐;通过 controlAlign="right" 右对齐控件,或在 FormField 上单独覆盖。较宽的字段可设置 layout="vertical",它仍然默认占满一行。description 解释字段含义,help 是控件下方的提示,error 会替代 help。
import { Form, FormField, Select, Switch, Textarea } from '@ifhover/leaf-ui';
export function FormSettings() {
return (
<Form layout="settings">
<FormField label="界面语言">
<Select
name="language"
defaultValue="zh-CN"
options={[
{ value: 'zh-CN', label: '简体中文' },
{ value: 'en-US', label: 'English' },
]}
/>
</FormField>
<FormField label="自动保存" description="编辑时自动保存更改。">
<Switch name="autoSave" defaultChecked />
</FormField>
<FormField
label="个人简介"
description="向其他成员介绍自己。"
layout="vertical"
help="最多 120 个字符。"
>
<Textarea name="biography" rows={3} maxLength={120} />
</FormField>
</Form>
);
}
调整设置控件列宽
右侧控件列默认占用扣除标签列和列间距后的剩余宽度。需要兼容固定控件列的场景时,仍可设置 settingsControlWidth;数字按像素处理,字符串可以使用 rem、百分比或 clamp() 等 CSS 值。Form 或视口较窄时,字段会自动改为上下排列。
settingsControlWidth 只用于需要固定右侧控件列的场景。FormField 可覆盖单个字段,ConfigProvider 可设置应用或区域的默认值。
<Form layout="settings" settingsControlWidth={240}>
<FormField label="界面语言">...</FormField>
<FormField label="自动保存" settingsControlWidth="18rem">...</FormField>
</Form>
<ConfigProvider components={{ Form: { settingsControlWidth: 'clamp(220px, 36%, 300px)' } }}>
<App />
</ConfigProvider>
需要关联应用 CSS 变量时,可通过同名组件变量覆盖;style 中的值优先于 settingsControlWidth。
import { Form, type LeafThemeStyle } from '@ifhover/leaf-ui';
const formStyle = {
'--leaf-form-settings-control-width': 'var(--app-settings-control-width)',
} satisfies LeafThemeStyle;
<Form layout="settings" style={formStyle}>
...
</Form>;
动态表单列表
FormList 管理列表项的值和增删、排序操作。使用 field.key 作为 React key,并把 field.name 传给实际控件;移动后索引与名称会更新。非受控列表在表单重置时恢复 defaultValue。
name 只是字段名前缀;点号名称在 FormData 中仍是普通字符串,不会自动生成嵌套对象。
import { Button, Flex, Form, FormField, FormGroup, FormList, Input } from '@ifhover/leaf-ui';
export function ExtensionDemo() {
return (
<Form onSubmit={(event) => event.preventDefault()}>
<FormGroup legend="联系人">
<FormList name="contacts" defaultValue={['']}>
{(fields, operations) => (
<>
{fields.map((field) => (
<FormField key={field.key} label={`联系人 ${field.index + 1}`}>
<Flex direction="column" gap="sm">
<Input
name={field.name}
type="email"
placeholder="hello@example.com"
value={field.value}
onChange={(event) => operations.update(field.index, event.target.value)}
/>
<Flex gap="sm" wrap>
<Button onClick={() => operations.remove(field.index)}>移除</Button>
<Button
disabled={field.index === 0}
onClick={() => operations.move(field.index, field.index - 1)}
>
上移
</Button>
</Flex>
</Flex>
</FormField>
))}
<FormField>
<Flex gap="sm" wrap>
<Button onClick={() => operations.add('')}>添加联系人</Button>
<Button type="reset" variant="outline">
重置
</Button>
</Flex>
</FormField>
</>
)}
</FormList>
</FormGroup>
</Form>
);
}
错误汇总
在同一 Form 内放置 FormErrorSummary,汇总字段校验错误。提交空表单后,点击汇总项可以聚焦对应控件。
import { Button, Flex, Form, FormErrorSummary, FormField, Input } from '@ifhover/leaf-ui';
export function FormSummary() {
return (
<Form onSubmit={(event) => event.preventDefault()}>
<FormErrorSummary />
<FormField label="姓名" required>
<Input name="name" />
</FormField>
<FormField label="邮箱" required>
<Input name="email" type="email" />
</FormField>
<FormField>
<Flex gap="sm" wrap>
<Button type="submit" variant="solid">
检查表单
</Button>
<Button type="reset" variant="outline">
重置
</Button>
</Flex>
</FormField>
</Form>
);
}
业务校验
useFormValidation 读取 FormData,管理错误和 pending 状态。使用 noValidate 接管校验,把按字段名返回的错误传给 FormField。此例进行同步校验,输入时清除当前字段错误。
import { Button, Flex, Form, FormField, Input, Text, useFormValidation } from '@ifhover/leaf-ui';
import { useState } from 'react';
export function FormValidation() {
const [saved, setSaved] = useState('');
const validation = useFormValidation({
validate: (data) => {
const errors: Record<string, string> = {};
if (!String(data.get('name') ?? '').trim()) errors.name = '请输入姓名';
return errors;
},
onSubmit: (data) => setSaved(String(data.get('name')).trim()),
});
return (
<Form
noValidate
onSubmit={validation.handleSubmit}
onReset={(event) => {
validation.handleReset(event);
setSaved('');
}}
>
<FormField label="姓名" required error={validation.errors.name}>
<Input
name="name"
onChange={() => {
validation.clearErrors('name');
setSaved('');
}}
/>
</FormField>
<FormField>
<Flex gap="sm" wrap>
<Button type="submit" loading={validation.pending}>
保存
</Button>
<Button type="reset" variant="outline">
重置
</Button>
</Flex>
</FormField>
{saved && (
<FormField>
<Text role="status" tone="muted">
已保存:{saved}
</Text>
</FormField>
)}
</Form>
);
}
异步 validate 和 onSubmit 应响应传入的 AbortSignal。新的提交会取消旧请求;clearErrors 也会取消当前请求。把 handleReset 绑定到表单重置事件,以取消请求并清除错误。
下面是第三方集成代码,文档站不加载 React Hook Form,因此不提供实时预览。请先在应用中安装依赖;原生输入使用 register,返回业务值的控件使用 Controller。
npm install react-hook-form
import { Button, Form, FormField, Input, Select } from '@ifhover/leaf-ui';
import { Controller, useForm } from 'react-hook-form';
export function AccountForm() {
const { register, control, handleSubmit, formState: { errors } } = useForm({
defaultValues: { email: '', role: '' },
});
return (
<Form noValidate onSubmit={handleSubmit((values) => console.log(values))}>
<FormField label="邮箱" error={errors.email?.message}>
<Input {...register('email', { required: '请输入邮箱' })} />
</FormField>
<Controller
name="role"
control={control}
rules={{ required: '请选择角色' }}
render={({ field, fieldState }) => (
<FormField label="角色" error={fieldState.error?.message}>
<Select {...field} options={[{ value: 'editor', label: '编辑者' }]} />
</FormField>
)}
/>
<Button type="submit">保存</Button>
</Form>
);
}
数组字段使用 React Hook Form 的 useFieldArray 管理。
API
表单接入
FormData 的值是字符串或 File;数字转换和对象组装由应用处理。未勾选的复选框不会提交 false;同名字段用 getAll() 读取。非受控字段由原生重置恢复默认值,受控字段需要应用同步重置状态。
Leaf UI 控件会读取 FormField 的关联信息。原生或第三方控件需要自行设置匹配的 id 与 htmlFor。Form disabled 只向支持表单上下文的控件传递禁用状态,不会禁用任意 DOM 元素或阻止提交。
关联字段名称、控件与校验信息的参数。
表单字段组的图例与说明参数。
动态表单列表的数据、字段命名与渲染参数。
传给列表渲染函数的单个字段信息。
动态表单列表的增删、移动与更新方法。
集中展示字段校验错误的参数。
错误汇总中的字段标识、名称和错误消息。
useFormValidation 返回的状态与表单事件处理方法。
业务校验、提交回调与错误处理配置。