暫無描述

index.tsx 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 | null
  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('container');
  15. const { children, visible, onCancel, container = DEFAULT_CONTAINER } = this.props
  16. let finalMountContainer: HTMLElement = document.body;
  17. if (!container) {
  18. if (!DEFAULT_CONTAINER) {
  19. if (!Modal.hasShowWarning) {
  20. Modal.hasShowWarning = true;
  21. }
  22. finalMountContainer = document.body;
  23. } else {
  24. if (!Modal.hasShowWarning) {
  25. Modal.hasShowWarning = true;
  26. }
  27. finalMountContainer = DEFAULT_CONTAINER;
  28. }
  29. }
  30. return visible && createPortal(
  31. <div className={ styles.wrapper }>
  32. <div
  33. className={ styles.overlay }
  34. onClick={ onCancel }
  35. />
  36. <div
  37. className={ styles.container }
  38. >
  39. { children }
  40. </div>
  41. </div>,
  42. finalMountContainer,
  43. )
  44. }
  45. }
  46. export default Modal;