默写一个简单的虚拟DOM

现刻

`<html>
<body>
</body>
<script>

class Element{
    constructor(tagName, props, children) {
        this.tagName = tagName
        this.props = props
        this.children = children
    }

    render () {
        const {tagName, props, children=[]} = this

        const el = document.createElement(tagName)

        for(const att in props) {
            el.setAttribute(att,props[att])
        }

        children.forEach(function(child){
            const childEl = child instanceof Element ? child.render() : document.createTextNode(child)

            el.appendChild(childEl)
        })

        return el
    }
}

function el (tagName, props, children) {
    return new Element(tagName, props, children)
}

const ul = el('ul',{class: 'list'},[
        el('li',{class: 'item'},['1','-']),
        el('li',{class: 'item'},['2',2,false]),
        el('li',{class: 'item'},['3']),
    ])

document.querySelector('body').appendChild(ul.render())

</script>
</html>`

打开编辑器默写虚拟DOM,如果运行错误就重写,你是在第几次完成的呢?

阅读 328

勤思笃行

168 声望
0 粉丝
0 条评论

勤思笃行

168 声望
0 粉丝
文章目录
宣传栏