Form#
@rockshin/tao-ui管理表单值、校验规则、提交状态与字段布局。
#何时使用
多个字段需要统一的数据收集、校验和提交生命周期时使用 Form。
Form 的直接子级 Form.Item 在有提示行时默认保留 4px 底部间距(--tao-size-unit),其余字段为 20px(--tao-padding-md);--tao-form-field-item-gap 可覆盖两者。放入 Stack 或 FormSection 后由容器管理间距;noStyle 不产生外壳或间距,独立 FormField 的布局不变。
默认 12–14px 提示字号下,预留行高为 18px,加上 2px 上间距和 4px 下间距,提示区域合计 24px。自定义更大的提示字号时,行高可随之增长。
Form.Item 配有校验规则,或显式设置 help、extra、validateStatus 时,在控件下方预留一行提示空间。单行校验消息出现和消失时不会挤动后续字段或按钮;长文案换行时允许自然撑高,避免遮挡内容。没有校验或提示的字段不预留空行。手动控制提示时,可用 help="" 保留空提示行。
推荐
- 校验消息说明问题和恢复方式。
- 按用户任务组织字段,而不是按数据模型机械排列。
- 通过
setFields(包括受控fields属性)写入的值会清掉该字段因旧值产生的残留校验错误;需要在同一条目里直接提供新的校验状态时,可同时传errors/warnings。
避免
- 不要为单个无校验输入引入完整 Form。
#代码演示
#基础用法
import { useState } from 'react';
import { Button, Form, Input } from '@rockshin/tao-ui';
function FormExample() {
const [feedback, setFeedback] = useState('');
return (
<>
<Form
initialValues={{ email: '' }}
onFinish={(values) => setFeedback(JSON.stringify(values))}
style={{ maxWidth: 400 }}
>
<Form.Item
name="email"
label="Email"
rules={[{ required: true, message: 'Enter your email.' }]}
>
<Input placeholder="you@example.com" />
</Form.Item>
<Button type="submit">Create account</Button>
</Form>
<output
aria-live="polite"
style={{
display: 'block',
marginTop: 12,
whiteSpace: 'pre-wrap',
overflowWrap: 'anywhere',
}}
>
{feedback}
</output>
</>
);
}
export default FormExample;#表单校验
import { useState } from 'react';
import { Button, Form, Input } from '@rockshin/tao-ui';
function ValidatedForm() {
const [feedback, setFeedback] = useState('');
return (
<>
<Form
onFinish={(values) => setFeedback(JSON.stringify(values))}
style={{ maxWidth: 420 }}
>
<Form.Item
name="username"
label="Username"
rules={[
{ required: true, message: 'Enter a username.' },
{ min: 3, message: 'Use at least 3 characters.' },
]}
>
<Input placeholder="username" />
</Form.Item>
<Form.Item
name="email"
label="Email"
rules={[{ required: true, message: 'Enter an email.' }]}
>
<Input type="email" placeholder="you@example.com" />
</Form.Item>
<Button type="submit">Submit</Button>
</Form>
<output
aria-live="polite"
style={{
display: 'block',
marginTop: 12,
whiteSpace: 'pre-wrap',
overflowWrap: 'anywhere',
}}
>
{feedback}
</output>
</>
);
}
export default ValidatedForm;#水平布局
import { Button, Form, Input } from '@rockshin/tao-ui';
function HorizontalForm() {
return (
<Form layout="horizontal" style={{ maxWidth: 560 }}>
<Form.Item name="name" label="Name">
<Input placeholder="Project name" />
</Form.Item>
<Form.Item name="slug" label="Slug">
<Input placeholder="project-name" />
</Form.Item>
<Button type="submit">Create project</Button>
</Form>
);
}
export default HorizontalForm;#完整表单
组合字段、分组和操作区,在一个页面中展示实际填写与提交路径。
Basic details about you.
Optional. Used for recovery.
Configure your workspace.
import {
Button,
FormActions,
FormField,
FormLayout,
FormSection,
Input,
Select,
Stack,
} from '@rockshin/tao-ui';
export default function FormCompleteForm() {
return (
<FormLayout>
<FormSection
title="Personal Information"
description="Basic details about you."
>
<Stack direction="horizontal" gap="md">
<FormField label="First name" required>
<Input value="Rihua" />
</FormField>
<FormField label="Last name" required>
<Input value="Chen" />
</FormField>
</Stack>
<FormField label="Email" required>
<Input value="rihua@example.com" prefix={<span>✉️</span>} />
</FormField>
<FormField label="Phone" description="Optional. Used for recovery.">
<Input placeholder="138 0000 0000" prefix={<span>+86</span>} />
</FormField>
</FormSection>
<FormSection title="Preferences" description="Configure your workspace.">
<FormField label="Language">
<Select
options={[
{ label: '简体中文', value: 'zh' },
{ label: 'English', value: 'en' },
]}
value="zh"
/>
</FormField>
<FormField label="Timezone">
<Select
options={[
{ label: 'Asia/Shanghai (UTC+8)', value: 'cst' },
{ label: 'America/New_York (UTC-5)', value: 'est' },
]}
value="cst"
/>
</FormField>
</FormSection>
<FormActions>
<Button variant="ghost">Cancel</Button>
<Button variant="primary">Save Changes</Button>
</FormActions>
</FormLayout>
);
}#跨字段校验
使用其他字段的值进行校验,并在相关值变化后更新反馈。
import { Button, Form, FormActions, Input, Stack } from '@rockshin/tao-ui';
export default function FormFormCrossField() {
return (
<Form layout="horizontal" style={{ maxWidth: 460 }}>
<Stack gap="md">
<Form.Item
name="password"
label="Password"
rules={[{ required: true, message: 'Password is required' }]}
>
<Input type="password" />
</Form.Item>
<Form.Item
name="confirm"
label="Confirm"
dependencies={['password']}
rules={[
({ getFieldValue }) => ({
validator: (_, value) =>
!value || getFieldValue('password') === value
? Promise.resolve()
: Promise.reject(new Error('Passwords do not match')),
}),
]}
>
<Input type="password" />
</Form.Item>
<FormActions>
<Button type="submit" variant="primary">
Change password
</Button>
</FormActions>
</Stack>
</Form>
);
}#动态字段列表
用 Form.List 增加和移除重复字段,表单值与字段索引同步维护。
import { useState } from 'react';
import { Button, Form, FormActions, Input, Stack } from '@rockshin/tao-ui';
export default function FormFormDynamicList() {
const [feedback, setFeedback] = useState('');
return (
<>
<Form
style={{ maxWidth: 400 }}
initialValues={{ members: [''] }}
onFinish={(values) => setFeedback(JSON.stringify(values, null, 2))}
>
<Stack gap="md">
<Form.List name="members">
{(fields, { add, remove }) => (
<>
{fields.map((field, index) => (
<Stack
key={field.key}
direction="horizontal"
gap="sm"
align="start"
>
<Form.Item
name={field.name}
label={index === 0 ? 'Members' : undefined}
noStyle={index !== 0}
rules={[{ required: true, message: 'Required' }]}
>
<Input placeholder="member name" />
</Form.Item>
<Button variant="ghost" onClick={() => remove(field.name)}>
Remove
</Button>
</Stack>
))}
<Button variant="secondary" onClick={() => add()}>
Add member
</Button>
</>
)}
</Form.List>
<FormActions>
<Button type="submit" variant="primary">
Save
</Button>
</FormActions>
</Stack>
</Form>
<output
aria-live="polite"
style={{
display: 'block',
marginTop: 12,
whiteSpace: 'pre-wrap',
overflowWrap: 'anywhere',
}}
>
{feedback}
</output>
</>
);
}#滚动到理赔字段
使用 Form.useForm()、Form 的 ref 或 Form.useFormInstance() 获取实例。支持数组路径和 Form.List 完整路径,例如 ['claims', 0, 'email']。
import { Button, Form, Input } from '@rockshin/tao-ui';
export default function ScrollToClaimField() {
const [form] = Form.useForm();
return (
<div style={{ height: 320, display: 'flex', flexDirection: 'column', gap: 12 }}>
<Button
style={{ flexShrink: 0 }}
onClick={() => form.scrollToField(['claimant', 'email'], {
behavior: 'smooth', block: 'center', focus: true,
})}
>
定位并聚焦邮箱
</Button>
<Form form={form} style={{ minHeight: 0, flex: 1, overflowY: 'auto' }}>
<p>向下滚动,或点击按钮定位字段。</p>
<div aria-hidden="true" style={{ height: 360 }} />
<Form.Item name={['claimant', 'email']} label="申请人邮箱">
<Input placeholder="claim@example.com" />
</Form.Item>
<div aria-hidden="true" style={{ height: 160 }} />
</Form>
</div>
);
}默认使用 scrollMode: 'if-needed' 和 block: 'nearest'。可传入 behavior、block、inline、boundary、scrollMode 等选项,focus: true 会在发起滚动后聚焦控件。只定位已挂载字段;条件渲染或未挂载的 Tab 内容需要先展开。自定义控件必须转发 ref(DOM 或带 nativeElement 的实例)或 id。
<Form
form={form}
onFinishFailed={({ errorFields }) => {
if (errorFields.length) {
form.scrollToField(errorFields[0].name, { focus: true });
}
}}
/>#API
#Form
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| layout | Label/control arrangement inherited by Form.Item. Defaults to 'vertical'. | "vertical" | "horizontal" | undefined | - |
| size | Cascades a control size to everything inside the form. | TaoSize | undefined | - |
| disabled | Disables every tao-ui control inside the form (e.g. while submitting). | boolean | undefined | - |