Antd表单多提交按钮区分:如何获取点击的按钮名称
解决Antd表单多提交按钮区分点击源的问题
Antd Form的onFinish默认只会返回表单字段值,不会携带提交按钮的信息,你可以通过以下几种方式实现区分:
方法1:给按钮绑定独立点击事件,手动触发验证与提交
取消按钮的htmlType="submit",改为在onClick中手动调用表单的validateFields,验证通过后携带按钮标识执行对应逻辑:
import React from "react"; import "./index.css"; import { Button, Form, Input, Select } from "antd"; import type { FormInstance } from "antd/es/form"; const { Option } = Select; const layout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } }; const tailLayout = { wrapperCol: { offset: 8, span: 16 } }; const App: React.FC = () => { const formRef = React.useRef<FormInstance>(null); // 通用处理函数,接收按钮标识 const handleSubmit = async (buttonType: string) => { try { const values = await formRef.current?.validateFields(); console.log(`点击了${buttonType}`, values); // 根据buttonType执行不同业务逻辑 if (buttonType === "submit1") { // Submit1的业务逻辑 } else if (buttonType === "submit2") { // Submit2的业务逻辑 } } catch (errorInfo) { console.log("表单验证失败:", errorInfo); } }; return ( <Form {...layout} ref={formRef} name="control-ref" style={{ maxWidth: 600 }} > {/* 原有表单字段保持不变 */} <Form.Item name="note" label="Note" rules={[{ required: true }]}> <Input /> </Form.Item> <Form.Item name="gender" label="Gender" rules={[{ required: true }]}> <Select placeholder="Select a option and change input text above"> <Option value="male">male</Option> <Option value="female">female</Option> <Option value="other">other</Option> </Select> </Form.Item> <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender } > {({ getFieldValue }) => getFieldValue("gender") === "other" ? ( <Form.Item name="customizeGender" label="Customize Gender" rules={[{ required: true }]} > <Input /> </Form.Item> ) : null } </Form.Item> <Form.Item {...tailLayout}> {/* 去掉htmlType="submit",绑定onClick传递标识 */} <Button type="primary" onClick={() => handleSubmit("submit1")}> Submit1 </Button> <Button type="primary" onClick={() => handleSubmit("submit2")} style={{ marginLeft: 8 }}> Submit2 </Button> </Form.Item> </Form> ); }; export default App;
方法2:通过隐藏字段记录点击的按钮
在表单中添加一个隐藏的Form.Item,点击按钮时先设置该字段的值,再触发表单提交,这样onFinish就能拿到按钮标识:
import React from "react"; import "./index.css"; import { Button, Form, Input, Select } from "antd"; import type { FormInstance } from "antd/es/form"; const { Option } = Select; const layout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } }; const tailLayout = { wrapperCol: { offset: 8, span: 16 } }; const App: React.FC = () => { const formRef = React.useRef<FormInstance>(null); const onFinish = (values: any) => { console.log("表单值:", values); // 通过hiddenButton字段区分按钮 if (values.hiddenButton === "submit1") { // Submit1逻辑 } else if (values.hiddenButton === "submit2") { // Submit2逻辑 } // 提交后可以清空隐藏字段 formRef.current?.setFieldsValue({ hiddenButton: "" }); }; const handleButtonClick = (buttonType: string) => { // 设置隐藏字段值 formRef.current?.setFieldsValue({ hiddenButton: buttonType }); // 触发表单提交 formRef.current?.submit(); }; return ( <Form {...layout} ref={formRef} name="control-ref" onFinish={onFinish} style={{ maxWidth: 600 }} > {/* 隐藏字段,用于记录点击的按钮 */} <Form.Item name="hiddenButton" style={{ display: "none" }} /> {/* 原有表单字段保持不变 */} <Form.Item name="note" label="Note" rules={[{ required: true }]}> <Input /> </Form.Item> <Form.Item name="gender" label="Gender" rules={[{ required: true }]}> <Select placeholder="Select a option and change input text above"> <Option value="male">male</Option> <Option value="female">female</Option> <Option value="other">other</Option> </Select> </Form.Item> <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender } > {({ getFieldValue }) => getFieldValue("gender") === "other" ? ( <Form.Item name="customizeGender" label="Customize Gender" rules={[{ required: true }]} > <Input /> </Form.Item> ) : null } </Form.Item> <Form.Item {...tailLayout}> <Button type="primary" onClick={() => handleButtonClick("submit1")}> Submit1 </Button> <Button type="primary" onClick={() => handleButtonClick("submit2")} style={{ marginLeft: 8 }}> Submit2 </Button> </Form.Item> </Form> ); }; export default App;
方法3:利用Form的submit事件参数(Antd 4.x+)
Antd的Form在提交时,onFinish的第二个参数包含提交事件对象,可通过事件对象获取触发提交的元素信息:
// 修改onFinish函数 const onFinish = (values: any, { event }: any) => { const buttonName = (event?.target as HTMLButtonElement).name; console.log(`点击了${buttonName}`, values); if (buttonName === "submit1") { // 逻辑1 } else if (buttonName === "submit2") { // 逻辑2 } };
注意:这种方法依赖原生DOM事件,若表单存在自定义提交逻辑或事件被阻止冒泡,可能无法正常获取,优先推荐方法1或2。
内容的提问来源于stack exchange,提问作者Ranjan Kumar
相关产品推荐
相关产品推荐

