#95 Virtual DOM(二)


  • 0
    administrators

    Virtual DOM 的基础上给 VNode 类添加 render 方法,render 方法把一个虚拟的 DOM 节点渲染成真正的 DOM 节点,例如:

    const ul = h('ul', {id: 'list', style: 'color: red'}, [
      h('li', {class: 'item'}, ['Item 1']),
      h('li', {class: 'item'}, ['Item 2']),
      h('li', {class: 'item'}, ['Item 3'])
    ]
    
    const urlDom = ul.render() // 渲染 DOM 节点和它的子节点
    ulDom.getAttribute('id') === 'list' // true
    ulDom.querySelectorAll('li').length === 3 // true
    

  • 1

    能把这题的题柄再明确下么
    代码栏里是写这些么

    class VNode() {
      constructor(...) {
          ...
      }
    
      render() {
        ...
      }
    }

  • 2

    class VNode {
      constructor(tagName, props, children) {
        this.tagName = tagName;
        this.props = props;
        this.children = children;
      }
      
      render() {
        const dom = document.createElement(this.tagName)
        if (this.props) {
          const props = Object.keys(this.props);
          props.map(prop => {
            dom.setAttribute(prop, this.props[prop]);
          })
        }
        
        if (this.children) {
          this.children.map(child => {
            dom.appendChild(child instanceof VNode ? child.render() : document.createTextNode(child));
          })
        }
        return dom;
      }
    }
    
    const h = (tagName, props, children) => new VNode(tagName, props, children)
    
    
    

  • 0
    管理员

    class VNode {
      constructor (tagName, props, children) {
        this.tagName = tagName
        this.props = props
        this.children = children
      } 
    
      render () {
        const { props, children } = this,
          dom = document.createElement(this.tagName)
        Object.entries(props).forEach(([key, value]) => dom.setAttribute(key, value))
        children.forEach(o => dom.appendChild(o instanceof VNode ? o.render() : document.createTextNode(o)))
        return dom
      }
    }
    
    const h = (tagName, props, children) => new VNode(tagName, props, children)
    

  • 0

    @yyssjj33 会因为这个报错吗?


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待