实现render函数

2020-04-03  本文已影响0人  Chris__Liu

将树状标签转换渲染为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)

上一篇 下一篇

猜你喜欢

热点阅读