-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathdom.tsx
42 lines (39 loc) · 1.03 KB
/
dom.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import React from 'react';
import { createRoot } from 'react-dom/client';
export interface PortalDOM {
element: HTMLDivElement;
mount: (component: React.ReactNode) => void;
unmount: () => void;
}
/**
*
* 组件可以通过函数的第一个参数传递进去
*
* @param point HTMLElement 挂载点,如果未指定,则挂载点为body
* @returns CreatePortalDOMResult
*/
export function createPortalDOM(point?: HTMLElement): PortalDOM {
const container = document.createElement('div');
let mountPoint: HTMLElement = document.body;
if (point instanceof HTMLElement) {
mountPoint = point;
}
mountPoint.appendChild(container);
const root = createRoot(container);
return {
element: container,
mount(component) {
root.render(component);
},
unmount() {
root.unmount();
if (container instanceof HTMLDivElement) {
if (typeof container.remove === 'function') {
container.remove();
} else {
mountPoint.removeChild(container);
}
}
},
};
}