手写-将虚拟 Dom 转化为真实 Dom
kingcwt2020-9-9前端javascript
let vdom = {
tag: 'DIV',
attrs: {
id: 'app'
},
children: [
{
tag: 'SPAN',
children: [
{ tag: 'A', children: 'hellow a' },
{ tag: 'A', children: [] }
]
},
{
tag: 'SPAN',
children: [
{ tag: 'A', children: [] },
{ tag: 'A', children: [] }
]
}
]
};
答案
let _render = (vnode) => {
if (typeof vnode === "number") {
vnode = String(vnode);
}
if (typeof vnode === 'string') {
return document.createTextNode(vnode);
}
if (vnode.tag) {
let dom = document.createElement(vnode.tag);
if (vnode.attrs) {
Object.keys(vnode.attrs).map(key => {
let value = vnode.attrs[key];
dom.setAttribute(key, value);
})
}
if (typeof vnode.children === 'string') {
dom.innerHTML = vnode.children;
}
if (Array.isArray(vnode.children)) {
vnode.children.forEach(child => {
dom.appendChild(_render(child));
});
}
return dom;
}
}