跳到主要内容

快速开始

本页用于把第一个 DynamicForm 跑起来。先完成安装、最小配置和提交处理;需要更多字段、联动或扩展时,再进入对应专题文档。

安装

pnpm add @whynotsnow/dynamic-form antd react react-dom

如果在本仓库内调试 demos,依赖已经由 workspace 管理,可以直接运行:

pnpm run start

本地 demo server 默认运行在 http://localhost:3000

渲染第一个表单

import { Form } from 'antd';
import { DynamicForm, useInitHandlers } from '@whynotsnow/dynamic-form';
import type { FormConfig } from '@whynotsnow/dynamic-form';

const formConfig: FormConfig = {
fields: [
{
id: 'name',
label: '姓名',
component: 'TextInput',
rules: [{ required: true, message: '请输入姓名' }]
},
{
id: 'email',
label: '邮箱',
component: 'TextInput',
componentProps: { placeholder: 'name@example.com' },
rules: [{ type: 'email', message: '邮箱格式不正确' }]
}
]
};

export function BasicForm() {
const [form] = Form.useForm();
const { isInitialized } = useInitHandlers({});

if (!isInitialized) return null;

return (
<DynamicForm
form={form}
formConfig={formConfig}
onSubmit={(values) => {
console.log(values);
}}
/>
);
}

这里已经包含三个最常用的入口:

  • FormConfig:描述字段、组件、初始值、校验和 UI 配置。
  • useInitHandlers:初始化默认 effect handlers。
  • DynamicForm:接收 Ant Design form 实例和 formConfig,并负责渲染与提交。

增加分组

字段较多时,可以用 groups 表达业务区块。默认渲染会把每个 group 放进 Ant Design Card

const formConfig: FormConfig = {
groups: [
{
id: 'profile',
title: '基础信息',
fields: [
{ id: 'name', label: '姓名', component: 'TextInput' },
{ id: 'phone', label: '手机号', component: 'TextInput' }
]
}
]
};

字段和 group 的详细配置见 配置指南

使用 4.0 节点树

需要嵌套区块、嵌套提交值或重复项时,可以使用 nodesnodes 中的 container 会渲染为默认 Card,并把自己的 name 作为子字段的 Ant Design 值路径前缀:

const formConfig: FormConfig = {
nodes: [
{
nodeType: 'container',
id: 'profile',
title: '资料',
name: 'profile',
children: [
{
nodeType: 'field',
id: 'profileName',
label: '姓名',
component: 'TextInput'
}
]
}
]
};

提交值形状为 { profile: { profileName: string } }profileName 这个 id 仍然用于 Runtime、effect graph 和 meta 更新。

加一个简单联动

通过 dependents 声明依赖字段,通过 effect 返回字段状态或 UI 更新。

const formConfig: FormConfig = {
fields: [
{
id: 'hasCompany',
label: '是否有公司',
component: 'Switch',
dependents: ['companyName'],
componentProps: { checkedChildren: '是', unCheckedChildren: '否' }
},
{
id: 'companyName',
label: '公司名称',
component: 'TextInput',
initialVisible: false,
effect: (_changedValue, allValues) => ({
visible: allValues.hasCompany === true
})
}
]
};

默认 handlers 支持 valuevisibledisabledreadonlycomponentPropsformItemProps 等返回 key。更完整的说明见 Effect 与处理器

下一步