1.直接封装这个新增修改的表单
import {
ModalForm,
ProForm,
ProFormSelect,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Form } from 'antd';
import { Button, Flex } from 'antd/lib';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
// 接口
import {jiekou} from '../service';
export type newDialogRef = {
/**打开 */
open(value?: lexingname & { id: string }): void;
};
type AfterAction = {
/**表单提交后*/
after(): void;
};
const Index = forwardRef<newDialogRef, AfterAction>((props, ref) => {
const [isOpen, setIsOpen] = useState(false);
const [form] = Form.useForm<lexingname>();
const hasId = useRef('');
const title = hasId.current ? '修改' : '新增';
const open: newDialogRef['open'] = (value) => {
const id = value?.id || '';
hasId.current = id;
/**对话框标题*/
const type = id ? 'edit' : 'add';
switch (type) {
case 'add': {
form.resetFields();
break;
}
case 'edit': {
if (value) {
form.setFieldsValue(value);
// 这儿可以替换修改获取的数据
}
break;
}
}
setIsOpen(true);
};
/**在使用 ref 时自定义暴露给父组件的实例值*/
useImperativeHandle(ref, () => ({
open,
}));
const {
data: jiekouData,
run: jiekouRun,
loading: jiekouLoading,
} = useRequest(jiekou, { manual: true });
return (
<>
{/* 对话框 */}
<ModalForm
title={title}
open={isOpen}
form={form}
modalProps={{
// 重置表单
destroyOnClose: true,
onCancel: () => {
setIsOpen(false);
},
}}
// 提交按钮相关配置
submitter={{
render(props) {
return (
<Flex gap={10} justify="end">
<Button onClick={() => setIsOpen(false)}>取消</Button>
<Button
type="primary"
onClick={() => {
props.submit();
}}
loading={jiekouLoading}
>
确定
</Button>
</Flex>
);
},
}}
// 提交数据时触发,return true关闭抽屉
onFinish={async (values) => {
await jiekouRun({ ...values });
form.resetFields();
props.after();
return true;
}}
>
<ProForm.Group>
<ProFormSelect
// col-md一般用于中屏设备, (min-width:992px);
width="md"
name="id"
label="名称"
placeholder="请选择名称"
rules={[{ required: true }]}
/>
</ProForm.Group>
</ModalForm>
</>
);
});
Index.displayName = 'newDialog';
export default Index;
2.父组件中使用
import { ActionType } from '@ant-design/pro-components';
import { useRef } from 'react';
// 子组件的位置
import ChildrenDialog, { newDialogRef } from './ChildrenDialog';
export default () => {
const actionRef = useRef<ActionType>(null);
/**给对话框传数据,newDialogRef是子组件中定义的*/
const sendDialogRef = useRef<newDialogRef>(null);
return (
<>
<ChildrenDialog
ref={sendDialogRef}
after={() => {
// 刷新
actionRef.current?.reload();
}}
/>
</>
);
};