Twlig / issuesBlog

MIT License
3 stars 0 forks source link

手写render函数 #97

Open Twlig opened 2 years ago

Twlig commented 2 years ago
function render(domNode) {
    if(typeof domNode === 'string') {
        return domNode
    }
    var tag = domNode.tagName
    var props = domNode.props
    var children = domNode.children
    var root
    if(tag) {
        root = document.createElement(tag)
    }
    if(props) {
        for(let key in props) {
            root.setAttribute(key, props[key])
        }
    }
    children.forEach(node => {
        var val = render(node) 
        if(typeof val === 'string') {
            root.innerHTML = val
        } else {
            root.appendChild(val)
        }
    })
    return root
}
render(domNode)
let domNode = {
  tagName: 'ul',
  props: { class: 'list' },
  children: [{
    tagName: 'li',
    children: ['toutiao']
  }, {
    tagName: 'li',
    children: ['douyin']
  }]
};