创建一个 Modal
import React, { useState, forwardRef, useImperativeHandle } from 'react';
import { Modal } from 'antd';
type TableItem = {
key: React.Key;
name: string;
diff: number;
temp: number;
};
interface RefProps {
handleOpen: (resData: any) => void;
handleClose: () => void;
}
interface DefaultProps {
title:string;
}
export interface TestModalRefProps extends RefProps {}
const TestModal = forwardRef<RefProps, DefaultProps>(({ title }, ref) => {
const [visible, setVisible] = useState<boolean>(false);
const [dataSource, setDataSource] = useState<TableItem[]>();
useImperativeHandle(
ref,
(): RefProps => ({
handleOpen,
handleClose,
}),
);
function handleOpen(resData: any): void {
setVisible(true);
setDataSource(resData);
}
function handleClose(): void {
setVisible(false);
}
return (
<Modal
title={title}
width={1200}
destroyOnClose={true}
visible={visible}
onOk={handleClose}
onCancel={handleClose}
footer={false}
>
content
</Modal>
);
});
export default TestModal;
父组件中使用
import React, {useRef}
import TestModal, { TestModalRefProps} from "TestModal";
const Parent: React.FC = () => {
const TestMOdalRef = useRef<TestModalRefProps>(null);
return (
<div>
<Button onCLick={ ()=> TestMOdalRef.current?.handleOpen([]) }></Buttom>
<TestModal ref={TestMOdalRef}></TestModal>
</div>
);
};
export default Parent;