创建虚拟 DOM

2019-05-26  本文已影响0人  _zk
        function Element(tagName, props, children) {
            this.tagName = tagName;
            this.props = props;
            this.children = children;
        }
        Element.prototype.render = function() {
            // 创建元素
            var element = document.createElement(this.tagName);
            // 获取属性
            var props = this.props;
            for (let propName in props) {
                let propValue = props[propName];
                // 挂载元素属性
                element.setAttribute(propName, propValue);
            }
            // 获取子节点
            var children = this.children || [];
            children.forEach((child) => {
                // 遍历子节点是否为文字节点
                var childElement = (child instanceof Element) ? child.render() : document.createTextNode(child);
                element.appendChild(childElement);
            });
            // 返回创建元素
            return element;
        };
        // 创建实例
        var ul = new Element(
            'ul', {
                id: 'list'
            }, [
                new Element(
                    'li', {
                        class: 'list-item'
                    }, ['item-1']
                ),
                new Element(
                    'li', {
                        class: 'list-item'
                    }, ['item-1']
                ),
                new Element(
                    'li', {
                        class: 'list-item'
                    }, ['item-1']
                ),
                new Element(
                    'li', {
                        class: 'list-item'
                    }, ['item-1']
                ),
            ]
        );
        // 创建真实 DOM
        var rootElement = ul.render();
        // 将 DOM 挂载到 body 上
        document.body.appendChild(rootElement);
上一篇 下一篇

猜你喜欢

热点阅读