实现简单render函数

什么是Virtual Dom

React和Vue2都使用了Virtual Dom技术,Virtual Dom并不是真正意义上的Dom,而是一个轻量级的JavaScript对象,在状态发生变化时,Virtual Dom会进行Diff运算,来更新只需要被替换的DOM,而不是全部重绘。
与DOM操作相比,Virtual Dom是基于JavaScript计算的,所以开销会小很多。

什么是render函数

Render函数通过Element的参数来创建Virtual Dom,结构精简,代码少且清晰,这里使用了一个demo实例来说明

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            margin-left: 50px;
            background-color: bisque;
        }
    </style>
</head>
<body>
    <div>

    </div>
    <script>
        const elementObj = {
            tagName: 'div',
            props: {'class': 'list'},
            children: [
                {tagName: 'div', props: {'class': 'list'}, content:"1",
                children: [
                    {tagName: 'div', props: {'class': 'list'}, content:"一"},
                    {tagName: 'div', props: {'class': 'list'}, content:"二",
                        children: [
                            {tagName: 'div', props: {'class': 'list'}, content:"①"},
                            {tagName: 'div', props: {'class': 'list'}, content:"②"}
                        ]
                    }
            ]},
                {tagName: 'div', props: {'class': 'list'}, content:"2",
                children: [
                    {tagName: 'div', props: {'class': 'list'}, content:"一"},
                    {tagName: 'div', props: {'class': 'list'}, content:"二"}
                ]
                }
            ]
        };

        document.querySelector('div').appendChild(render(elementObj));
        //深度遍历
        function render (elementObj) {
            //首先生成父元素
            let el = document.createElement(elementObj.tagName);
            for(propName in elementObj.props){
                propValue = elementObj.props[propName];
                el.setAttribute(propName, propValue);
            }
            if (elementObj.content) {
                console.log(elementObj.content);
                el.innerText = elementObj.content;
            }
            //如果children不为空
            if (elementObj.children) {
                elementObj.children.forEach(function(child){
                    el.appendChild(render(child));
                    }
                );
            }
            return el;
        }
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/HelloJC/p/11208605.html