import React, { useEffect, useRef } from 'react'; import ReactDOM from 'react-dom'; import Close from '@components/icons/close'; import Button from '@components/button'; import './index.less'; interface Props { getTarget?: () => HTMLElement | null, visible?: boolean, onClose?: (...args: any[]) => void, destroyOnClose?: boolean, children: any, } interface ModalInterface extends React.FC { create: (...args: any[]) => any, confirm: (...args: any[]) => any, } const Modal:ModalInterface = (props: any) => { const elRef = useRef(document.createElement('div')); useEffect(() => { const rootEl = props.getTarget() || document.body; if (props.visible) { rootEl && rootEl.appendChild(elRef.current); } else { rootEl && rootEl.contains(elRef.current) && rootEl.removeChild(elRef.current); } }, [props.visible]); return ReactDOM.createPortal(
props.onClose && props.onClose()}/>
{(props.destroyOnClose && !props.visible) ? null : props.children}
, elRef.current, ) } Modal.create = (props: any) => { const el = document.createElement('div'); function close() { rootEl && rootEl.contains(el) && rootEl.removeChild(el); } ReactDOM.render(
{props.content(close)}
, el, ); const rootEl = props.target || document.body; rootEl && rootEl.appendChild(el); return { close: () => { rootEl && rootEl.contains(el) && rootEl.removeChild(el); } } } Modal.confirm = (props: any) => { const el = document.createElement('div'); function close() { rootEl && rootEl.contains(el) && rootEl.removeChild(el); } ReactDOM.render(
{ props.title &&
{props.title}
}
{props.content(close)}
{/*
取消
*/} {/*
确认
*/}
, el, ); const rootEl = props.target || document.body; rootEl && rootEl.appendChild(el); return { close: () => { rootEl && rootEl.contains(el) && rootEl.removeChild(el); } } } export default Modal;