【前端芝士树】模拟虚拟DOM挂载
【前端芝士树】虚拟DOM挂载是如何实现的
问题描述
给出如下虚拟dom的数据结构,如何实现简单的虚拟dom,渲染到目标dom树
//样例数据 let demoNode = ({ tagName: 'ul', props: {'class': 'list'}, children: [ ({tagName: 'li', children: ['douyin']}), ({tagName: 'li', children: ['toutiao']}) ] });
渲染结果如下所示:
<ul class="list"> <li>douyin</li> <li>toutiao</li> </ul>
用innerHTML实现RenderNode
/** * @param node * @return {string} * */ function RenderNode(node) { let result=''; if(typeof node === 'string'){ result += node; } else if(Array.isArray(node)){ node.forEach(item => { result += RenderNode(item); }); }else{ let tag = node.tagName || 'div'; let props = ''; if (node.props) { let nodeProps = node.props; for (let key in nodeProps) { props += (` ${key}="${nodeProps[key]}"`); } } if(node.children && node.children.length){ result = `<${tag + props}>${RenderNode(node.children)}</${tag}>`; } } return result; } let renderHTML = RenderNode(demoNode); console.log(renderHTML); let main = document.getElementById('main'); main.innerHTML = renderHTML;
相关推荐
星星有所不知 2020-10-12
zuncle 2020-09-28
huaoa 2020-09-14
北京老苏 2020-08-17
luvhl 2020-08-17
Kakoola 2020-07-29
drdrsky 2020-07-29
书虫媛 2020-07-08
liaoxuewu 2020-07-08
SIMONDOMAIN 2020-07-08
爱读书的旅行者 2020-07-07
tianzyc 2020-07-04
Vue和React是数据驱动视图,如何有效控制DOM操作?能不能把计算,更多的转移为js计算?因为js执行速度很快。patch函数-->patch,对比tag,对比tag与key,对比children
Lophole 2020-07-04
Lophole 2020-06-28
liaoxuewu 2020-06-26
ApeLife技术 2020-06-26
北京老苏 2020-06-25
Lophole 2020-06-14