如何在Ant Design动态表单中为每个字段区域设置独立提交按钮
Ant Design 动态表单单区块独立校验提交实现方案
核心原理:Ant Design Form 组件的 validateFields 方法支持传入指定字段路径数组,仅对匹配的字段做校验,不会触发其他字段的校验逻辑。
实现步骤
- 从 Form.List 渲染回调的 field 参数中获取当前区块的索引
field.name,绑定到当前区块的提交按钮点击事件上 - 构造当前区块所有表单项对应的字段路径数组,路径格式为
[区块索引, 字段名] - 调用
form.validateFields(构造的字段路径数组),仅校验当前区块的字段 - 校验通过后,从返回结果中提取当前区块的数据,执行对应提交逻辑即可
- 单独删除逻辑直接使用 Form.List 提供的
remove方法传入当前区块索引即可,本身就是单区块操作
核心代码示例
Form.List 渲染部分
import { Form, Input, InputNumber, Button } from 'antd'; const DynamicForm = () => { const [form] = Form.useForm(); // 单区块提交逻辑 const handleBlockSubmit = async (blockIndex) => { try { // 构造当前区块的所有字段路径,按实际业务字段调整 const currentBlockFields = [ [blockIndex, 'username'], [blockIndex, 'age'], [blockIndex, 'email'] ]; // 仅校验当前区块字段 const formValues = await form.validateFields(currentBlockFields); // 提取当前区块数据 const currentBlockData = formValues[blockIndex]; // 此处写提交逻辑:接口请求、数据处理等 console.log('当前区块提交数据:', currentBlockData); } catch (err) { // 校验失败时AntD会自动展示对应字段错误提示,无需额外处理 console.error('当前区块校验失败', err); } }; return ( <Form form={form} name="dynamic_block_form"> <Form.List name="blockList"> {(fields, { add, remove }) => ( <> {fields.map((field) => ( <div key={field.key} style={{ border: '1px solid #eee', padding: 16, marginBottom: 16 }}> <Form.Item name={[field.name, 'username']} label="用户名" rules={[{ required: true, message: '请输入用户名' }]} > <Input placeholder="请输入用户名" /> </Form.Item> <Form.Item name={[field.name, 'age']} label="年龄" rules={[{ required: true, message: '请输入年龄' }]} > <InputNumber placeholder="请输入年龄" style={{ width: '100%' }} /> </Form.Item> <Form.Item name={[field.name, 'email']} label="邮箱" rules={[{ required: true, type: 'email', message: '请输入合法邮箱' }]} > <Input placeholder="请输入邮箱" /> </Form.Item> <div> <Button type="primary" onClick={() => handleBlockSubmit(field.name)}> 提交当前区块 </Button> <Button danger onClick={() => remove(field.name)} style={{ marginLeft: 8 }}> 删除当前区块 </Button> </div> </div> ))} <Button type="dashed" onClick={() => add()} block> 新增字段区块 </Button> </> )} </Form.List> </Form> ); };
注意事项
如果区块内的字段是动态生成的,可通过 form.getFieldsValue() 获取全量表单数据后,动态提取当前区块的所有字段名,构造校验字段数组即可,无需硬编码字段名。
内容的提问来源于stack exchange,提问作者Nemus
相关产品推荐
相关产品推荐

