首页 > 其他分享 >Antd Modal组件的封装 Modal.show

Antd Modal组件的封装 Modal.show

时间:2022-10-26 14:38:03浏览次数:51  
标签:const show element return Modal props Antd onOk

antd的modal组件,使用的时候,一般都需要手动去修改visible属性,创建编辑共用的时候,需额外维护数据。然后就想着封装一套不需要维护数据的Modal

1、onOk返回promise的时候,执行resolve会关闭弹窗,执行reject不关闭弹窗。不返回Promise的时候,点击会关闭弹窗
2、content 放Modal里面的JSX
3、该组件的api和Modal的api一样
使用示例:

const handleClick = () => {   const { hide } = Modal.show({     title: '新建',     content: (       <div>456</div>     ),     cancelText: '取消',     okText: '确认',     onOk: () => {       // 可不需要返回Promise       return new Promise((resolve, reject) => {         reject();       })     },     onCancel: () => {       hide();     }   }) }   封装源码 import React, { forwardRef } from 'react'; import ReactDOM from 'react-dom'; import { Modal as AntdModal } from 'antd';
const Modal = (props) => {   const { visible, children, ...rest } = props;   return (     <>       <AntdModal         {...rest}         visible={visible}       >         {           typeof children === 'object' ? React.Children.map(children, child => React.cloneElement(child)) : children         }       </AntdModal>     </>   ) }
const forwardRefModal = forwardRef(Modal); export default forwardRefModal;
forwardRefModal.show = (props) => {   const { title, content, ...rest } = props;   let element = document.createElement('div');   document.body.appendChild(element);   const onClose = () => {     ReactDOM.render(getModalNode({ visible: false }), element)   }   const afterClose = () => {     ReactDOM.unmountComponentAtNode(element);     element.remove();     element = null;     if (props.afterClose && typeof props.afterClose === 'function') {       props.afterClose();     }   }   const onOk = () => {     if (props.onOk && typeof props.onOk === 'function') {       const maybePromise = props.onOk();       if (maybePromise instanceof Promise) {         maybePromise           .then(() => {             onClose();           })       } else {         onClose();       }       return;     }     onClose();   }   const getModalNode = ({ visible }) => {     let modalNode = null;     modalNode = (       <Modal         {...rest}         visible={visible}         title={title}         afterClose={afterClose}         onOk={onOk}       >         {content}       </Modal>     )     return modalNode;   }   ReactDOM.render(getModalNode({ visible: true }), element)   return {     hide: onClose   } }

 

标签:const,show,element,return,Modal,props,Antd,onOk
From: https://www.cnblogs.com/hamili/p/16828240.html

相关文章