React-domdiff(4)
Yu Lei 2019-5-28
React
dom-diff
React dom-diff
dom-diff 是通过 js 的计算返回一个 patch 对象,即补丁对象,通过特定的操作解析 patch 对象经行页面的重新渲染。
实现的步骤
- js 对象转换成虚拟 DOM
- 虚拟 DOM 转换成真实 DOM 插入页面
- 有事件发生修改虚拟 DOM
- 比较两颗 DOM 树 找到差异对象
- 差异对象补丁到真实 DOM
简单实现虚拟 DOM
//实现DOM 插入页面
class Element {
constructor(tarname, atts, children) {
this.tagname = tarname
this.attrs = atts
this.children = children || []
}
render() {
let element = document.createElement(this.tagname)
for (let attr in this.attrs) {
this.setAttr(element, attr, this.attrs[attr])
}
//先序深度优先遍历
this.children.forEach(child => {
let childElement = (child instanceof Element) ? child.render() : document.createTextNode(child)
element.appendChild(childElement)
});
return element
}
setAttr = (element, attr, value) => {
switch (attr) {
case "style":
element.style.cssText = value
break;
case "value":
let tagname = element.tagname.toLowerCase()
if (tagname === 'input' || tagname === "textarea") {
element.value = value
} else {
element.setAttribute(attr, value)
}
break;
default:
element.setAttribute(attr, value)
break;
}
}
}
export default Element
//使用
import ELement from './ELement'
let ul1 = new ELement(
'ul', {
class: 'nav'
},
[
new ELement(
'li', {
class: 'item'
},
['1']
),
new ELement(
'li', {
class: 'item'
},
['2']
),
new ELement(
'li', {
class: 'item'
},
['3']
)
]
)
let root = ul1.render()
export default root
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
实现 DOM-diff
再 react 中只能实现同级别的 DOM 于虚拟 DOM 之间的比较 如果发生不同则修改,如果整个 DOM 移动到子节点下面,react 是感知不到的,react 会把整个子节点删除掉 然后重新生成子节点。
- DOM 节点的跨层级移动操作特别少,可以忽略不计
- 拥有相同类的两个组件会生成相似的树形结构,拥有不同类的两个组件将会生成不同的树形结构
- 对于同一层级的一组节点,它们可以通过唯一的 key 进行区分,开发人员可以使用一个
key
指示在不同的渲染中那个那些元素可以保持稳定。