2019-07-03 20:14:39 +08:00
---
order: 14
title:
zh-CN: 弹出层中的新建表单
en-US: Form in Modal to Create
---
## zh-CN
当用户访问一个展示了某个列表的页面,想新建一项但又不想跳转页面时,可以用 Modal 弹出一个表单,用户填写必要信息后创建新的项。
2021-04-14 19:00:01 +08:00
> 🛎️ 想要 3 分钟实现?试试 ProForm 的 [Modal 表单](https://procomponents.ant.design/components/form#modal-%E8%A1%A8%E5%8D%95)!
2020-11-27 18:29:21 +08:00
2019-07-03 20:14:39 +08:00
## en-US
When user visit a page with a list of items, and want to create a new item. The page can popup a form in Modal, then let user fill in the form to create an item.
```tsx
2022-05-23 14:37:16 +08:00
import { Button, Form, Input, Modal, Radio } from 'antd';
2020-01-22 12:11:49 +08:00
import React, { useState } from 'react';
2019-07-03 20:14:39 +08:00
interface Values {
title: string;
description: string;
modifier: string;
}
interface CollectionCreateFormProps {
2022-08-23 16:55:57 +08:00
open: boolean;
2019-07-03 20:14:39 +08:00
onCreate: (values: Values) => void;
onCancel: () => void;
}
const CollectionCreateForm: React.FC< CollectionCreateFormProps > = ({
2022-08-23 16:55:57 +08:00
open,
2019-07-03 20:14:39 +08:00
onCreate,
onCancel,
}) => {
const [form] = Form.useForm();
return (
< Modal
2022-08-23 16:55:57 +08:00
open={open}
2019-07-03 20:14:39 +08:00
title="Create a new collection"
okText="Create"
cancelText="Cancel"
onCancel={onCancel}
onOk={() => {
form
.validateFields()
.then(values => {
form.resetFields();
onCreate(values);
})
.catch(info => {
console.log('Validate Failed:', info);
});
}}
>
< Form
form={form}
layout="vertical"
name="form_in_modal"
initialValues={{ modifier: 'public' }}
>
< Form.Item
name="title"
label="Title"
rules={[{ required: true, message: 'Please input the title of collection!' }]}
>
< Input / >
< / Form.Item >
< Form.Item name = "description" label = "Description" >
< Input type = "textarea" / >
< / Form.Item >
< Form.Item name = "modifier" className = "collection-create-form_last-form-item" >
< Radio.Group >
< Radio value = "public" > Public< / Radio >
< Radio value = "private" > Private< / Radio >
< / Radio.Group >
< / Form.Item >
< / Form >
< / Modal >
);
};
2022-05-19 09:46:26 +08:00
const App: React.FC = () => {
2022-08-23 16:55:57 +08:00
const [open, setOpen] = useState(false);
2019-07-03 20:14:39 +08:00
2020-12-17 15:09:18 +08:00
const onCreate = (values: any) => {
2019-07-03 20:14:39 +08:00
console.log('Received values of form: ', values);
2022-08-23 16:55:57 +08:00
setOpen(false);
2019-07-03 20:14:39 +08:00
};
return (
< div >
< Button
type="primary"
onClick={() => {
2022-08-23 16:55:57 +08:00
setOpen(true);
2019-07-03 20:14:39 +08:00
}}
>
New Collection
< / Button >
< CollectionCreateForm
2022-08-23 16:55:57 +08:00
open={open}
2019-07-03 20:14:39 +08:00
onCreate={onCreate}
onCancel={() => {
2022-08-23 16:55:57 +08:00
setOpen(false);
2019-07-03 20:14:39 +08:00
}}
/>
< / div >
);
};
2022-05-19 09:46:26 +08:00
export default App;
2019-07-03 20:14:39 +08:00
```
```css
.collection-create-form_last-form-item {
margin-bottom: 0;
}
```