封装了弹窗功能的对象。这个对象提供了一些方法来显示和隐藏弹窗,以及处理弹窗的确认和取消操作。
这个对象的success方法创建了一个新的DOM元素,并使用ReactDOM.render将一个空的
渲染到这个元素上,然后将这个元素添加到文档的body中。
另外,onCancel和onOk方法在调用传入的回调函数之后会移除弹窗。这是一个好的做法,但是你可能也想要在success方法中处理这些回调函数,以便在用户点击确认或取消按钮时可以执行相应的操作。
最后,removeDom方法移除了弹窗的DOM元素。
import React from 'react';
import './index.scss';
import { createRoot } from 'react-dom/client';
const BanAreaPopups = {
dom: null as HTMLElement | null,
root: null as ReturnType<typeof createRoot> | null,
success({
title,
tips,
handleOk,
handleCancel,
}: {
title: string;
tips: string;
handleOk?: () => void;
handleCancel?: () => void;
}) {
this.removeDom();
this.dom = document.createElement('div');
const handleWrapperClick = (e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === e.currentTarget) {
this.onCancel(handleCancel);
}
};
const JSXdom = (
<div className="modal-wrapper" onClick={handleWrapperClick}>
<div className="modal-content">
<h1>{title}</h1>
<p>{tips}</p>
<button onClick={() => this.onOk(handleOk)}>确认</button>
<button onClick={() => this.onCancel(handleCancel)}>取消</button>
</div>
</div>
);
this.root = createRoot(this.dom);
this.root.render(JSXdom);
document.body.appendChild(this.dom);
},
onCancel(handleCancel?: () => void) {
if (typeof handleCancel === 'function') {
handleCancel();
}
this.removeDom();
},
onOk(handleOk?: () => void) {
if (typeof handleOk === 'function') {
handleOk();
}
this.removeDom();
},
removeDom() {
if (this.dom) {
this.root?.unmount();
this.dom.remove();
this.dom = null;
this.root = null;
}
},
};
export default BanAreaPopups;