-
Notifications
You must be signed in to change notification settings - Fork 415
Expand file tree
/
Copy pathroot.ts
More file actions
47 lines (44 loc) · 1.32 KB
/
root.ts
File metadata and controls
47 lines (44 loc) · 1.32 KB
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
43
44
45
46
47
import { Container } from './hostConfig';
import {
updateContainer,
createContainer
} from 'react-reconciler/src/fiberReconciler';
import { ReactElement } from 'shared/ReactTypes';
import { initEvent, elementPropsKey } from './SyntheticEvent';
const containerToRoot = new Map();
function clearContainerDOM(container: Container) {
if (!container.hasChildNodes()) {
return;
}
for (let i = 0; i < container.childNodes.length; i++) {
const childNode = container.childNodes[i];
if (!Object.hasOwnProperty.call(childNode, elementPropsKey)) {
container.removeChild(childNode);
// 当移除节点时,再遍历时length会减少,所以相应i需要减少一个
i--;
}
}
}
export function createRoot(container: Container) {
let root = containerToRoot.get(container);
if (!root) {
root = createContainer(container);
containerToRoot.set(container, root);
} else {
throw '你在之前已经传递给createRoot()的container上调用了ReactDOM.createRoot()';
}
return {
render(element: ReactElement) {
if (containerToRoot.get(container) !== root) {
throw '不能更新一个卸载的root.';
}
clearContainerDOM(container);
initEvent(container, 'click');
return updateContainer(element, root);
},
unmount() {
containerToRoot.delete(container);
return updateContainer(null, root);
}
};
}