美文网首页
Virtual DOM转Real DOM过程

Virtual DOM转Real DOM过程

作者: lizhihua | 来源:发表于2016-07-24 13:07 被阅读97次
    Paste_Image.png

    app.js

    
    var el = require('./element')
    
    var ul = el('ul', {id: 'list'}, [
      el('li', {class: 'item'}, ['Item 1']),
      el('li', {class: 'item'}, ['Item 2']),
      el('li', {class: 'item'}, ['Item 3'])
    ])
    
    console.log(ul);
    
    var ulRoot = ul.render()
    document.body.appendChild(ulRoot)
    
    

    element.js

    
    function Element (tagName, props, children) {
      this.tagName = tagName
      this.props = props
      this.children = children
    }
    
    Element.prototype.render = function () {
      var el = document.createElement(this.tagName) // 根据tagName构建
      var props = this.props
    
      for (var propName in props) { // 设置节点的DOM属性
        var propValue = props[propName]
        el.setAttribute(propName, propValue)
      }
    
      var children = this.children || []
    
      children.forEach(function (child) {
        var childEl = (child instanceof Element)
          ? child.render() // 如果子节点也是虚拟DOM,递归构建DOM节点
          : document.createTextNode(child) // 如果字符串,只构建文本节点
        el.appendChild(childEl)
      })
    
      return el
    }
    
    module.exports = function (tagName, props, children) {
      return new Element(tagName, props, children)
    }
    
    

    相关文章

      网友评论

          本文标题:Virtual DOM转Real DOM过程

          本文链接:https://www.haomeiwen.com/subject/sdawjttx.html