Last active
          November 11, 2021 05:08 
        
      - 
      
 - 
        
Save jackluson/a8e74b0f67d93ee59b8614d6d280968b to your computer and use it in GitHub Desktop.  
    Modal with react
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import ReactDOM from 'react-dom'; | |
| import { useEffect } from 'react'; | |
| Modal._PortalStack = [] // 利用栈结构管理多个弹窗面板 | |
| function Modal(Component) { | |
| function Portal(props?: any) { | |
| useEffect(() => { | |
| document.body.appendChild(Portal._container); | |
| return () => { | |
| document.body.removeChild(Portal._container) | |
| } | |
| }, []) | |
| return ReactDOM.createPortal( | |
| <Component {...props} />, | |
| Portal._container, | |
| ) | |
| } | |
| Portal._container = null | |
| Portal.show = (props?: Record<string, any>) => { | |
| Modal._PortalStack.unshift(Portal) | |
| return new Promise<void>((resolve, reject) => { | |
| try { | |
| let _container = null; | |
| if (!_container) { | |
| _container = document.createElement('div'); | |
| } | |
| Portal._container = _container | |
| ReactDOM.render(<Portal {...props} />, Portal._container); | |
| resolve() | |
| } catch (error) { | |
| reject(error) | |
| } | |
| }) | |
| }; | |
| Portal.hide = () => { | |
| ReactDOM.unmountComponentAtNode(Portal._container) | |
| }; | |
| return Portal | |
| } | |
| Modal.hide = function () { | |
| return new Promise<void>((resolve, reject) => { | |
| try { | |
| Modal._PortalStack.shift().hide() | |
| resolve() | |
| } catch (error) { | |
| reject(error) | |
| } | |
| }) | |
| } | |
| Modal.use = function (Component) { | |
| return Modal(Component) | |
| } | |
| export default Modal | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment