Form 表单 #
概述 #
Form 表单组件是数据录入的核心组件,提供了完整的表单功能,包括数据收集、验证、提交等。
基础用法 #
基本表单 #
tsx
import { Form, Input, Button } from 'antd';
const onFinish = (values) => {
console.log('表单数据:', values);
};
<Form
name="basic"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
style={{ maxWidth: 600 }}
initialValues={{ remember: true }}
onFinish={onFinish}
autoComplete="off"
>
<Form.Item
label="用户名"
name="username"
rules={[{ required: true, message: '请输入用户名' }]}
>
<Input />
</Form.Item>
<Form.Item
label="密码"
name="password"
rules={[{ required: true, message: '请输入密码' }]}
>
<Input.Password />
</Form.Item>
<Form.Item wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">
提交
</Button>
</Form.Item>
</Form>
表单布局 #
水平布局 #
tsx
import { Form, Input, Button } from 'antd';
<Form layout="horizontal">
<Form.Item label="姓名" name="name">
<Input />
</Form.Item>
</Form>
垂直布局 #
tsx
import { Form, Input, Button } from 'antd';
<Form layout="vertical">
<Form.Item label="姓名" name="name">
<Input />
</Form.Item>
</Form>
行内布局 #
tsx
import { Form, Input, Button } from 'antd';
<Form layout="inline">
<Form.Item name="name">
<Input placeholder="姓名" />
</Form.Item>
<Form.Item>
<Button type="primary">搜索</Button>
</Form.Item>
</Form>
表单验证 #
内置规则 #
tsx
import { Form, Input } from 'antd';
<Form.Item
name="email"
label="邮箱"
rules={[
{ required: true, message: '请输入邮箱' },
{ type: 'email', message: '请输入有效的邮箱地址' },
]}
>
<Input />
</Form.Item>
自定义验证 #
tsx
import { Form, Input } from 'antd';
<Form.Item
name="password"
label="密码"
rules={[
{ required: true, message: '请输入密码' },
{ min: 6, message: '密码至少6位' },
{
validator: (_, value) =>
value && value.includes('A')
? Promise.resolve()
: Promise.reject(new Error('密码必须包含大写字母')),
},
]}
>
<Input.Password />
</Form.Item>
动态验证 #
tsx
import { Form, Input, Checkbox } from 'antd';
const form = Form.useFormInstance();
<Form.Item name="agree" valuePropName="checked">
<Checkbox>同意协议</Checkbox>
</Form.Item>
<Form.Item
name="phone"
label="手机号"
rules={[
{
required: form.getFieldValue('agree'),
message: '请输入手机号',
},
]}
>
<Input />
</Form.Item>
表单实例 #
使用 Form.useForm #
tsx
import { Form, Input, Button } from 'antd';
import { useState } from 'react';
const [form] = Form.useForm();
const onFinish = (values) => {
console.log('表单数据:', values);
};
const onReset = () => {
form.resetFields();
};
const onFill = () => {
form.setFieldsValue({
username: 'admin',
password: '123456',
});
};
<Form form={form} onFinish={onFinish}>
<Form.Item name="username" label="用户名">
<Input />
</Form.Item>
<Form.Item name="password" label="密码">
<Input.Password />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">提交</Button>
<Button onClick={onReset}>重置</Button>
<Button onClick={onFill}>填充</Button>
</Form.Item>
</Form>
常用方法 #
| 方法 | 说明 |
|---|---|
| getFieldValue | 获取字段值 |
| getFieldsValue | 获取多个字段值 |
| setFieldValue | 设置字段值 |
| setFieldsValue | 设置多个字段值 |
| resetFields | 重置字段 |
| validateFields | 验证字段 |
| submit | 提交表单 |
复杂表单 #
动态增减表单项 #
tsx
import { Form, Input, Button, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
<Form.List name="users">
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, ...restField }) => (
<Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
<Form.Item
{...restField}
name={[name, 'first']}
rules={[{ required: true, message: '请输入名' }]}
>
<Input placeholder="名" />
</Form.Item>
<Form.Item
{...restField}
name={[name, 'last']}
rules={[{ required: true, message: '请输入姓' }]}
>
<Input placeholder="姓" />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(name)} />
</Space>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
添加用户
</Button>
</Form.Item>
</>
)}
</Form.List>
嵌套表单 #
tsx
import { Form, Input } from 'antd';
<Form.Item label="地址">
<Input.Group compact>
<Form.Item name={['address', 'province']} noStyle>
<Input style={{ width: '33%' }} placeholder="省" />
</Form.Item>
<Form.Item name={['address', 'city']} noStyle>
<Input style={{ width: '33%' }} placeholder="市" />
</Form.Item>
<Form.Item name={['address', 'street']} noStyle>
<Input style={{ width: '33%' }} placeholder="街道" />
</Form.Item>
</Input.Group>
</Form.Item>
表单联动 #
联动显示 #
tsx
import { Form, Input, Select } from 'antd';
const FormWithDependency = () => {
const [form] = Form.useForm();
const userType = Form.useWatch('type', form);
return (
<Form form={form}>
<Form.Item name="type" label="用户类型">
<Select>
<Select.Option value="personal">个人</Select.Option>
<Select.Option value="company">企业</Select.Option>
</Select>
</Form.Item>
{userType === 'company' && (
<Form.Item name="companyName" label="企业名称">
<Input />
</Form.Item>
)}
</Form>
);
};
shouldUpdate #
tsx
import { Form, Input, Select } from 'antd';
<Form.Item shouldUpdate={(prevValues, curValues) => prevValues.type !== curValues.type}>
{({ getFieldValue }) =>
getFieldValue('type') === 'company' ? (
<Form.Item name="companyName" label="企业名称">
<Input />
</Form.Item>
) : null
}
</Form.Item>
dependencies #
tsx
import { Form, Input } from 'antd';
<Form.Item
name="confirmPassword"
label="确认密码"
dependencies={['password']}
rules={[
({ getFieldValue }) => ({
validator(_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve();
}
return Promise.reject(new Error('两次密码不一致'));
},
}),
]}
>
<Input.Password />
</Form.Item>
API #
Form #
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| colon | 是否显示冒号 | boolean | true |
| form | 表单实例 | FormInstance | - |
| initialValues | 初始值 | object | - |
| labelAlign | 标签对齐 | left | right |
right |
| labelCol | 标签布局 | ColProps | - |
| layout | 表单布局 | horizontal | vertical | inline |
horizontal |
| name | 表单名称 | string | - |
| preserve | 保留字段值 | boolean | true |
| requiredMark | 必填标记 | boolean | optional |
true |
| scrollToFirstError | 提交失败滚动到第一个错误 | boolean | options | false |
| size | 组件尺寸 | small | middle | large |
- |
| validateMessages | 验证提示模板 | ValidateMessages | - |
| validateTrigger | 验证触发时机 | string | string[] | onChange |
| wrapperCol | 控件布局 | ColProps | - |
| onFinish | 提交回调 | (values) => void | - |
| onFinishFailed | 提交失败回调 | ({ values, errorFields, outOfDate }) => void | - |
| onFieldsChange | 字段变化回调 | (changedFields, allFields) => void | - |
| onValuesChange | 值变化回调 | (changedValues, allValues) => void | - |
Form.Item #
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| colon | 是否显示冒号 | boolean | true |
| dependencies | 依赖字段 | string[] | - |
| extra | 额外提示 | ReactNode | - |
| getValueFromEvent | 获取事件值 | (…args) => any | - |
| getValueProps | 获取值属性 | (value) => any | - |
| hasFeedback | 显示校验状态 | boolean | false |
| help | 提示信息 | ReactNode | - |
| hidden | 是否隐藏 | boolean | false |
| initialValue | 初始值 | string | - |
| label | 标签 | ReactNode | - |
| labelAlign | 标签对齐 | left | right |
- |
| labelCol | 标签布局 | ColProps | - |
| messageVariables | 消息变量 | Record<string, string> | - |
| name | 字段名 | string | string[] | - |
| normalize | 转换值 | (value, prevValue, prevAllValues) => any | - |
| noStyle | 无样式 | boolean | false |
| preserve | 保留字段值 | boolean | true |
| required | 必填 | boolean | false |
| rules | 校验规则 | Rule[] | - |
| shouldUpdate | 是否更新 | boolean | (prevValues, curValues) => boolean | false |
| tooltip | 提示信息 | ReactNode | TooltipProps | - |
| trigger | 收集值时机 | string | onChange |
| validateFirst | 是否先校验 | boolean | parallel |
false |
| validateStatus | 校验状态 | success | warning | error | validating |
- |
| validateTrigger | 校验触发时机 | string | string[] | - |
| valuePropName | 值属性名 | string | value |
| wrapperCol | 控件布局 | ColProps | - |
最佳实践 #
1. 表单重置 #
tsx
const [form] = Form.useForm();
const handleReset = () => {
form.resetFields();
};
2. 表单赋值 #
tsx
const [form] = Form.useForm();
useEffect(() => {
form.setFieldsValue({
username: 'admin',
email: 'admin@example.com',
});
}, []);
3. 表单提交 #
tsx
const handleSubmit = async (values) => {
try {
await submitForm(values);
message.success('提交成功');
form.resetFields();
} catch (error) {
message.error('提交失败');
}
};
下一步 #
接下来学习 Input 输入框 组件!
最后更新:2026-03-28