虚拟DOM就是用js对象来描述真实DOM结构
h('div','hello')>>>渲染器>>真实DOM
tag:用来描述标签名称
props:是个对象,用来描述标签属性和事件
children:用来描述标签子节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
const vnode = {
tag: 'div',
props: {
onClick: () => alert('hello')
},
children: 'click me'
}
function RenderDom(vnode, container) {
const el = document.createElement(vnode.tag)
for (const key in vnode.props) {
if (/^on/.test(key)) {
document.addEventListener
el.addEventListener(key.slice(2).toLowerCase(), vnode.props[key])
}
}
if (typeof vnode.children === 'string') {
el.appendChild(document.createTextNode(vnode.children))
// document.createTextNode
// document.appendChild
} else if (Array.isArray(vnode.children)) {
vnode.children.forEach(element => {
RenderDom(element, el)
});
}
container.appendChild(el)
}
RenderDom(vnode, document.body)
</script>
</html>