113. Virtual DOM I
分享给更多人
中等难度 -通过 / -执行
假设你已经完成了 110. 二叉树的序列化和反序列化,你是否想过对于DOM tree也可以做相同的事情?
HTML可以被当作某种意义上的 序列化→浏览器解释(反序列化)HTML文本→ 然后构建DOM tree。
除了基于XML的方案,我们也可以试试JSON。如果打印出React中对element的表示,像这样:
const el = <div>
<h1> this is </h1>
<p className="paragraph"> a <button> button </button> from <a href="https://bfe.dev"><b>BFE</b>.dev</a>
</p>
</div>;
console.log(el)
我们可以得到如下结果( ref和 key 等等非主要信息已去除)
{
type: 'div',
props: {
children: [
{
type: 'h1',
props: {
children: ' this is '
}
},
{
type: 'p',
props: {
className: 'paragraph',
children: [
' a ',
{
type: 'button',
props: {
children: ' button '
}
},
' from',
{
type: 'a',
props: {
href: 'https://bfe.dev',
children: [
{
type: 'b',
props: {
children: 'BFE'
}
},
'.dev'
]
}
}
]
}
}
]
}
}
很显然,这就是一个完成的树结构,不过是用object literal表述的。
好了,现在请你对DOM tree进行序列化和反序列化,就像上面React做的一样。
注意
事件处理函数或者自定义组建等使用到function的地方不再本体的考虑范围,你可以忽略而仅仅考虑标准HTML 标签。
你需要支持:
- TextNode (string) 作为子节点
- 单个子节点和多个子节点
- camelCase的属性
virtualize()
接受一个DOM tree 然后返回一个object literal的表达
render()
接受一个object literal格式的表达然后构建一个新的DOM tree。