用 JS 对象来描述

55 阅读1分钟
1.const vnode = {
      tag: 'div',
      props: {
        onClick: () => alert('hello')
      },
      children: 'click me'
    }


 function renderer(vnode, container) {
      // 使用 vnode.tag 作为标签名称创建DOM
      const el = document.createElement(vnode.tag)
      for (const key in vnode.props) {
        // 如果以 key 为开头,说明他是事件
        if (/^on/.test(key)) {
          el.addEventListener(key.substr(2).toLowerCase(),
            // 事件处理函数
            vnode.props[key])
        }
      }


      // 处理 children
      if (typeof vnode.children === 'string') {
        // 如果children是 sting ,说明他是文本的子节点
        el.appendChild(document.createTextNode(vnode.children))
      } else if (Array.isArray(vnode.children)) {
        // 递归地调用 renderer 函数渲染子节点,使用当前元素 el 作为挂载点
        vnode.children.forEach((child) => renderer(child, el))
      }


      // 将元素增加到挂载点下
      container.appendChild(el)
    }

    renderer(vnode, document.body)
   
   
   
  2.const title = {
      tag: 'h1',
      props: {
        onClick: handler,
      },
      children: [{
        tag: 'sapn'
      }]
    }