ant-design/components/form/demo/form-in-modal.tsx
叶枫 502dac12aa
docs: format code (#48309)
* docs: fix code

* feat: lint

* feat: prettier

* feat: test

* feat: review

* feat: format html

* feat: format html
2024-04-08 14:04:08 +08:00

116 lines
2.9 KiB
TypeScript

import React, { useEffect, useState } from 'react';
import type { FormInstance } from 'antd';
import { Button, Form, Input, Modal, Radio } from 'antd';
interface Values {
title?: string;
description?: string;
modifier?: string;
}
interface CollectionCreateFormProps {
initialValues: Values;
onFormInstanceReady: (instance: FormInstance<Values>) => void;
}
const CollectionCreateForm: React.FC<CollectionCreateFormProps> = ({
initialValues,
onFormInstanceReady,
}) => {
const [form] = Form.useForm();
useEffect(() => {
onFormInstanceReady(form);
}, []);
return (
<Form layout="vertical" form={form} name="form_in_modal" initialValues={initialValues}>
<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>
);
};
interface CollectionCreateFormModalProps {
open: boolean;
onCreate: (values: Values) => void;
onCancel: () => void;
initialValues: Values;
}
const CollectionCreateFormModal: React.FC<CollectionCreateFormModalProps> = ({
open,
onCreate,
onCancel,
initialValues,
}) => {
const [formInstance, setFormInstance] = useState<FormInstance>();
return (
<Modal
open={open}
title="Create a new collection"
okText="Create"
cancelText="Cancel"
okButtonProps={{ autoFocus: true }}
onCancel={onCancel}
destroyOnClose
onOk={async () => {
try {
const values = await formInstance?.validateFields();
formInstance?.resetFields();
onCreate(values);
} catch (error) {
console.log('Failed:', error);
}
}}
>
<CollectionCreateForm
initialValues={initialValues}
onFormInstanceReady={(instance) => {
setFormInstance(instance);
}}
/>
</Modal>
);
};
const App: React.FC = () => {
const [formValues, setFormValues] = useState<Values>();
const [open, setOpen] = useState(false);
const onCreate = (values: Values) => {
console.log('Received values of form: ', values);
setFormValues(values);
setOpen(false);
};
return (
<>
<Button type="primary" onClick={() => setOpen(true)}>
New Collection
</Button>
<pre>{JSON.stringify(formValues, null, 2)}</pre>
<CollectionCreateFormModal
open={open}
onCreate={onCreate}
onCancel={() => setOpen(false)}
initialValues={{ modifier: 'public' }}
/>
</>
);
};
export default App;