面试官:写一个虚拟dom并渲染叭。

383 阅读1分钟

虚拟dom其实就是js对象。就好比在内存里生成一个js对象,将它转换成真实的dom节点,并渲染到页面上。

代码

<!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>
    <script>
        class Element {
            constructor({ tagName, props, children }) {
                this.tagName = tagName;
                this.props = props;
                this.children = children;
            }

            render() {
                let el = document.createElement(this.tagName);
                let props = this.props;
                let propName, propValue;
                for (propName in props) {
                    propValue = props[propName];
                    el.setAttribute(propName, propValue);
                }

                this.children.forEach(function (child) {
                    let childEl = null;
                    if (child instanceof Element) {
                        childEl = child.render()
                    } else {
                        childEl = document.createTextNode(child);
                    }
                    el.appendChild(childEl)
                })
                return el;
            }
        }

        let ele = new Element({
            tagName: 'ul',
            props: { 'class': 'list' },
            children: [
                new Element({ tagName: 'li', children: ['我是子节点1'] }),
                new Element({ tagName: 'li', children: ['我是子节点2'] })
            ]
        })
        document.querySelector('body').appendChild(ele.render())
    </script>

</body>

</html>

效果

image.png


注意点
1.判断子节点是不是文本节点,可以使用instanceof来判断,再用createTextNode来生成文本节点。
2.传入的是一个js对象(一定注意),一般有三个属性:html标签(tagName)、属性名(props)、子节点(children)是一个数组。


记录记录!