import React from "react"; import { createPortal } from "react-dom"; import { isBrowser } from "../Utils/utils"; import styles from "./Modal.less"; export interface ModalProps { visible: boolean; onCancel: (e: any) => void; container?: HTMLElement; } export class Modal extends React.PureComponent { static hasShowWarning = false; render() { if (!isBrowser()) return null; // 服务端无需渲染下列代码,渲染也会出错 const DEFAULT_CONTAINER: HTMLElement | null = document.getElementById( "container" ); const { children, visible, onCancel, container } = this.props; let finalMountContainer: HTMLElement; if (!container) { if (!DEFAULT_CONTAINER) { if (!Modal.hasShowWarning) { Modal.hasShowWarning = true; } finalMountContainer = document.body; } else { if (!Modal.hasShowWarning) { Modal.hasShowWarning = true; } finalMountContainer = DEFAULT_CONTAINER; } } else { finalMountContainer = container; } return ( visible && createPortal(
{children}
, finalMountContainer ) ); } } export default Modal;