暂无描述

index.tsx 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import React from "react";
  2. import { createPortal } from "react-dom";
  3. import { isBrowser } from "../Utils/utils";
  4. import styles from "./Modal.less";
  5. export interface ModalProps {
  6. visible: boolean;
  7. onCancel: (e: any) => void;
  8. container?: HTMLElement;
  9. }
  10. export class Modal extends React.PureComponent<ModalProps> {
  11. static hasShowWarning = false;
  12. render() {
  13. if (!isBrowser()) return null; // 服务端无需渲染下列代码,渲染也会出错
  14. const DEFAULT_CONTAINER: HTMLElement | null = document.getElementById(
  15. "container"
  16. );
  17. const { children, visible, onCancel, container } = this.props;
  18. let finalMountContainer: HTMLElement;
  19. if (!container) {
  20. if (!DEFAULT_CONTAINER) {
  21. if (!Modal.hasShowWarning) {
  22. Modal.hasShowWarning = true;
  23. }
  24. finalMountContainer = document.body;
  25. } else {
  26. if (!Modal.hasShowWarning) {
  27. Modal.hasShowWarning = true;
  28. }
  29. finalMountContainer = DEFAULT_CONTAINER;
  30. }
  31. } else {
  32. finalMountContainer = container;
  33. }
  34. return (
  35. visible &&
  36. createPortal(
  37. <div className={styles.wrapper}>
  38. <div className={styles.overlay} onClick={onCancel} />
  39. <div className={styles.container}>{children}</div>
  40. </div>,
  41. finalMountContainer
  42. )
  43. );
  44. }
  45. }
  46. export default Modal;