我有一个antd表单,它有2个提交按钮,我必须在两个提交上执行不同的任务。为此,我们需要识别哪个按钮被点击,但我不能这样做。我试图获得点击的提交按钮的名称,但在提交时它只给出表单值,而不是按钮名称。下面是我的代码:
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);
};
return (
<Form
{...layout}
ref={formRef}
name="control-ref"
onFinish={onFinish}
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}>
<Button type="primary" name="submit1" htmlType="submit">
Submit1
</Button>
<Button type="primary" name="submit2" htmlType="submit">
Submit2
</Button>
</Form.Item>
</Form>
);
};
export default App;
1条答案
按热度按时间2hh7jdfx1#
你可以在第二个按钮中删除htmlType,并在第二个按钮中传递onClick函数。