[英]Antd form remote submit
I want to trigger the submit button outside the antd form我想在antd表单外触发提交按钮
Here is my code这是我的代码
<Form
{...layout}
name="basic"
initialValues={{
remember: true,
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: 'Please input your username!',
},
]}
>
<Input />
</Form.Item>
<Form.Item {...tailLayout}>
// Submit button here works well
</Form.Item>
</Form>
I want this outside form tag, please suggest我想要这个外部表单标签,请建议
<Button type="primary" htmlType="submit">
Submit
</Button>
You can try this way:你可以这样试试:
const [form] = Form.useForm();
const handleFinish = (values) => {
console.log("values: ", values);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<MyForm form={form} onFinish={handleFinish} />
<Button onClick={() => form.submit()}>Submit</Button>
</div>
);
export const MyForm = ({ form, onFinish }) => {
return (
<Form
form={form}
onFinish={onFinish}
initialValues={{ username: "John Doe" }}
>
<Form.Item name="username">
<Input />
</Form.Item>
</Form>
);
};
If the form and the button are not in the same component then it is hard to create same reference for the form in 2 different place.如果表单和按钮不在同一个组件中,那么很难在 2 个不同的地方为表单创建相同的引用。 But I found an other easy way:
但我找到了另一种简单的方法:
<Form id="myForm">...</>
...
<Button form="myForm" key="submit" htmlType="submit">
Submit
</Button>
This is the answer from this issue这是这个问题的答案
write a custom function like this:像这样编写自定义 function :
function handleSubmit(){
form.validateFields().then((values) => {
// do something with values
})
}
and call it from Button onClick.并从按钮 onClick 调用它。 so you don't need Form
onFinish
props.所以你不需要 Form
onFinish
道具。
sorry i was searching and see this old question.抱歉,我正在搜索并看到这个老问题。
as in the comment you should use const [form] = Form.useForm();
如评论中所述,您应该使用
const [form] = Form.useForm();
that's a lot of function you can use one of them is submit
.这是很多 function 你可以使用其中之一是
submit
。
form.submit();
you can refer to document and search for useform:您可以参考文档并搜索useform:
https://ant.design/components/form/ https://ant.design/components/form/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.