For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/llms-full.txt, and this page is available as Markdown at https://ifhover.github.io/leaf-ui/components/form.md.

Form 表单

组织字段、标签和校验提示,收集表单数据。

基础用法

为控件设置 name,通过提交事件中的 FormData 读取值。FormField required 配合输入类型进行原生校验,错误显示在对应字段下方。

用于接收项目通知
basic.tsx
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 值。长标签在指定宽度内换行。水平和设置布局在窄容器内自动上下排列。

label-width.tsx
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。

编辑时自动保存更改。
向其他成员介绍自己。
最多 120 个字符。
settings.tsx
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 中仍是普通字符串,不会自动生成嵌套对象。

联系人
extensions.tsx
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,汇总字段校验错误。提交空表单后,点击汇总项可以聚焦对应控件。

error-summary.tsx
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。此例进行同步校验,输入时清除当前字段错误。

validation.tsx
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

下面是第三方集成代码,文档站不加载 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

Form API

表单接入

FormData 的值是字符串或 File;数字转换和对象组装由应用处理。未勾选的复选框不会提交 false;同名字段用 getAll() 读取。非受控字段由原生重置恢复默认值,受控字段需要应用同步重置状态。

Leaf UI 控件会读取 FormField 的关联信息。原生或第三方控件需要自行设置匹配的 id 与 htmlFor。Form disabled 只向支持表单上下文的控件传递禁用状态,不会禁用任意 DOM 元素或阻止提交。

属性类型默认值说明
layout'horizontal' | 'vertical' | 'settings''horizontal'字段默认布局;settings 将标签与描述放在左侧,将控件放在右侧控件列。
labelWidthnumber | string112horizontal/settings 字段的标签列宽度;数字按像素处理,字符串接受 CSS 长度、百分比或 clamp() 等函数;可由 FormField.labelWidth 单独覆盖。
labelAlign'left' | 'right''right'horizontal 字段的标签对齐方向
controlAlign'left' | 'right''left'settings 字段控件在右侧控件列中的对齐方向。
settingsControlWidthnumber | string—可选的 settings 固定控件列宽度;省略时使用扣除标签列和间隙后的剩余宽度。数字按像素处理,字符串接受 CSS 长度、百分比或 clamp() 等函数。
disabledbooleanfalse禁用交互。
refRef<HTMLFormElement>—表单引用

FormField API

关联字段名称、控件与校验信息的参数。

属性类型默认值说明
labelReactNode—字段标签
htmlForstring自动生成与输入控件的 id 关联;一个字段对应一个控件或组
requiredbooleanfalse要求整体值非空,复合控件只校验一次。
helpReactNode—显示在控件下方的辅助提示,占据正常布局空间
errorReactNode—错误提示,优先于 help 展示
layoutFormProps['layout']继承 Form当前字段的布局;vertical 可用于占满整行的宽控件
labelWidthnumber | string—当前 horizontal/settings 字段的标签列宽度;数字按像素处理,字符串接受 CSS 长度、百分比或 clamp() 等函数。
controlAlignFormProps['controlAlign']继承 Form当前 settings 字段的控件对齐方向。
settingsControlWidthFormProps['settingsControlWidth']继承 Form当前 settings 字段的固定控件列宽度;省略时使用扣除标签列和间隙后的剩余宽度。
descriptionReactNode—标签下方的字段说明;与控件下方的 help 和 error 独立展示

FormGroupProps API

表单字段组的图例与说明参数。

属性类型默认值说明
legendReactNode—字段组名称
descriptionReactNode—补充说明

FormListProps API

动态表单列表的数据、字段命名与渲染参数。

属性类型默认值说明
namestring必填字段名前缀;将 field.name 用于实际控件,点号名称不自动生成嵌套对象。
valuereadonly T[]—受控值
defaultValuereadonly T[][]初始值;非受控表单 reset 时恢复
onChange(values: T[]) => void—值变化回调
itemKey(value: T) => string—提取稳定的项目标识
children(fields: readonly FormListField<T>[], operations: FormListOperations<T>) => ReactNode必填渲染列表项与操作的函数。

FormListField API

传给列表渲染函数的单个字段信息。

属性类型默认值说明
keystring必填唯一且稳定的标识
indexnumber必填当前索引,从 0 开始
namestring必填表单字段名称
valueT必填该行当前值。

FormListOperations API

动态表单列表的增删、移动与更新方法。

属性类型默认值说明
add(value: T, index?: number) => void必填插入字段,省略 index 时追加
remove(index: number | readonly number[]) => void必填移除一个或多个位置
move(from: number, to: number) => void必填移动字段并保留稳定 key
update(index: number, value: T) => void必填更新字段值

FormErrorSummaryProps API

集中展示字段校验错误的参数。

属性类型默认值说明
errorsreadonly FormError[]—省略时汇总同一 Form 内字段错误
titleReactNode语言默认值错误汇总标题,默认使用当前语言的提示。

FormError API

错误汇总中的字段标识、名称和错误消息。

属性类型默认值说明
fieldIdstring必填关联输入控件 id,点击错误后聚焦
messageReactNode必填错误内容
labelReactNode—显示内容

FormValidationApi

useFormValidation 返回的状态与表单事件处理方法。

属性类型默认值说明
errorsRecord<string, string>必填按字段名组织的错误,可传给 FormField。
pendingboolean必填校验或提交是否进行中。
setErrorsDispatch<SetStateAction<Record<string, string>>>必填设置服务端或业务错误。
handleSubmit(event: FormEvent<HTMLFormElement>) => Promise<void>必填绑定到 Form.onSubmit。
handleReset(event: FormEvent<HTMLFormElement>) => void必填绑定到 Form.onReset,取消请求并清除错误。
cancel() => void必填取消当前请求。
clearErrors(name?: string) => void必填清除一个或全部错误并取消旧请求。

FormValidationOptions

业务校验、提交回调与错误处理配置。

属性类型默认值说明
validate( data: FormData, signal: AbortSignal, ) => Record<string, string> | Promise<Record<string, string>>必填接收 FormData 和取消信号,返回按字段名组织的错误。
onSubmit(data: FormData, signal: AbortSignal) => void | Promise<void>—校验通过后提交;应响应取消信号。
onError(error: unknown) => void—校验或提交过程中抛出异常时调用。
focusErrorbooleantrue出现错误时聚焦第一个字段。