ReactDOMRoot类
# 概览
在React应用的入口会执行createRoot方法,而createRoot方法最后会返回ReactDOMRoot的实例对象
function createRoot(){
....
return new ReactDOMRoot(options)
}
1
2
3
4
2
3
4
本文主要介绍ReactDOMRoot的实现。
# 源码分析
ReactDOMRooT就是一个普通的函数,在其原型上定义了render和unmount方法,分别用于挂载渲染子节点和卸载应用。
function ReactDOMRoot(internalRoot) {
// 存储内部的Fiber 根节点
this._internalRoot = internalRoot;
}
/**
* createRoot(div).render(<App/>) render方法的实现就是如下
*/
ReactDOMRoot.prototype.render =
function (children) {
// 获取内部根节点
var root = this._internalRoot;
// 确保根节点存在
if (null === root) throw Error(formatProdErrorMessage(409));
// 获取当前的Fiber树根节点
var current = root.current,
// 请求一个更新车道:优先级
lane = requestUpdateLane();
// 调用 updateContainerImpl更新容器
updateContainerImpl(current, lane, children, root, null, null);
};
/**
* unmount方法:卸载应用的方法,会清理整个React应用
*/
ReactDOMRoot.prototype.unmount =
function () {
var root = this._internalRoot;
// 若根节点存在,则执行卸载
if (null !== root) {
// 清空内部节点引用
this._internalRoot = null;
// 获取容器DOM元素
var container = root.containerInfo;
// 第三个参数为null,表示卸载所有子节点,lane=2表示同步更新
updateContainerImpl(root.current, 2, null, root, null, null);
// 强制同步刷新工作,确保立即卸载
flushSyncWork$1();
// 清理容器DOM元素上的内部实例标记
container[internalContainerInstanceKey] = null;
}
};
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
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
编辑 (opens new window)
上次更新: 2026/01/24, 10:05:32