react 的 render 函数

JSON2DOM = react的render函数

功能介绍

const vnode = {
    
    
  tag: 'DIV',
  attrs: {
    
    
    id: 'app'
  },
  children: [
    {
    
    
      tag: 'SPAN',
      children: [
        {
    
    
          tag: 'A',
          children: [
            "text1"
          ]
        }
      ]
    },
    {
    
    
      tag: 'DIV',
      children: [
        {
    
    
          tag: 'SECTION',
          attrs: {
    
    
            class: 'box',
            'data-birthday': '02-17',
          },
          children: [
            666,
            {
    
    
              tag: 'h3',
              children: [
                "text2"
              ]
            },
            {
    
    
              tag: 'h4',
              children: [
                "text3"
              ]
            },
            {
    
    
              tag: 'h5',
              children: [
                "text4"
              ]
            }
          ]
        },
        {
    
    
          tag: 'A',
          attrs: {
    
    
            class: 'link',
            style: {
    
    
              color: 'red',
              'text-decoration': 'underline'
            }
          },
          children: [
            [1, 2, 3]
          ]
        }
      ]
    }
  ]
}
// 转化为下述 DOM 结构
<div id="app">
  <span>
    <a>text1</a>
  </span>
  <div>
    <section class="box" data-birthday="02-17">
      666
      <h3>text2</h3>
      <h4>text3</h4>
      <h5>text4</h5>
    </section>
    <a class="link" style="color: red; text-decoration: underline;">1,2,3</a>
  </div>
</div>

实现 _render 函数


function _render(vnode) {
    
    
  if (vnode === null || typeof vnode !== 'object') {
    
    
    return document.createTextNode(vnode);
  }
  if (Array.isArray(vnode)) {
    
    
    return document.createTextNode(vnode.toString());
  }

  let root = null;
  if (vnode.tag) {
    
    
    root = document.createElement(vnode.tag);
  }
  if (vnode.attrs) {
    
    
    Object.entries(vnode.attrs).forEach(item => {
    
    
      if (item[0] !== 'style') {
    
    
        root.setAttribute(item[0], item[1]);
      }
      else {
    
    
        root.style.cssText = Object.entries(item[1])
          .reduce((prev, curr) => (prev += `${
      
      curr[0]}:${
      
      curr[1]};`, prev), '');
      }
    })
  }
  if (vnode.children) {
    
    
    vnode.children.forEach(item => root.appendChild(_render(item)));
  }
  return root;
}

测试结果

猜你喜欢

转载自blog.csdn.net/ox4f5da2/article/details/128657399