antd的modal组件,使用的时候,一般都需要手动去修改visible属性,创建编辑共用的时候,需额外维护数据。然后就想着封装一套不需要维护数据的Modal
1、onOk返回promise的时候,执行resolve会关闭弹窗,执行reject不关闭弹窗。不返回Promise的时候,点击会关闭弹窗
2、content 放Modal里面的JSX
3、该组件的api和Modal的api一样
使用示例:
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