import * as React from 'react'; import { useEffect, useRef } from 'react'; import { createPortal } from 'react-dom'; import Button from '../Button'; import './index.less'; function PortalImpl({ onCancel, children, onOk, title, linkText, linkHref, visible = true, closeOnClickOutside }: ModalProps) { const modalRef: any = useRef(); useEffect(() => { if (modalRef.current !== null) { modalRef.current.focus(); } }, []); useEffect(() => { let modalOverlayElement: any = null; const handler = event => { event.preventDefault(); if (event.keyCode === 27) { onCancel && onCancel(event); } }; const clickOutsideHandler = (event: MouseEvent) => { const target = event.target; if (modalRef.current !== null && !modalRef.current.contains(target as Node) && closeOnClickOutside) { onCancel && onCancel(event); } }; if (modalRef.current !== null) { modalOverlayElement = modalRef.current?.parentElement; if (modalOverlayElement !== null && visible) { modalOverlayElement?.addEventListener('click', clickOutsideHandler); } } if (visible) { window.addEventListener('keydown', handler); } return () => { window.removeEventListener('keydown', handler); if (modalOverlayElement !== null) { modalOverlayElement?.removeEventListener('click', clickOutsideHandler); } }; }, [closeOnClickOutside, onCancel, visible]); return (
{title}
{children}
{linkText ? ( ) : ( )}
); } interface ModalProps { children: JSX.Element | string | (JSX.Element | string)[]; closeOnClickOutside?: boolean; onCancel?: (e) => void; onOk?: (e) => void; title: string; visible?: boolean; linkText: string; linkHref: string; } export default function Modal(props: ModalProps): JSX.Element { return createPortal(, document.body); }