将树状标签转换渲染为dom节点,利用createElement创建节点,递归渲染子节点
let ast = {
tag: 'div',
attr: {
'class': 'parent',
'key': 1
},
text: 1,
children: [
{
tag: 'div',
attr: {
'class': 'child',
'key': 1
},
text: 2,
children: [
{
tag: 'text',
attr: {
'class': 'child',
'key': 1
},
text: 2,
},
{
tag: 'div',
attr: {
'class': 'child',
'key': 2
},
text: 3,
}
]
},
{
tag: 'div',
attr: {
'class': 'child',
'key': 2
},
text: 3,
}
]
}
const render = ($el, container) => {
// 根节点
let root
if( Object.prototype.toString.call($el) === "[object String]" ){
root = document.querySelector($el)
}else{
root = $el
}
const { tag, attr, text, children } = container
let element = document.createElement(tag)
for (key in attr) {
element.setAttribute(key, attr[key])
}
element.innerText = text
if (children) {
children.forEach((item) => {
render(element,item)
})
}
root.appendChild(element)
}
render('#root', ast)
![](https://img.haomeiwen.com/i8562733/6690d430b492a894.png)
网友评论