首頁  >  文章  >  web前端  >  如何寫出自己的虛擬DOM?方法介紹

如何寫出自己的虛擬DOM?方法介紹

青灯夜游
青灯夜游轉載
2020-10-29 17:30:212609瀏覽

如何寫出自己的虛擬DOM?方法介紹

要建立自己的虛擬DOM,需要知道兩件事。你甚至不需要深入 React 的源代碼或深入任何其他虛擬DOM實現的源代碼,因為它們是如此龐大和複雜——但實際上,虛擬DOM的主要部分只需不到50行代碼。

有兩個概念:

  • Virtual DOM 是真實DOM的映射
  • 當虛擬DOM 樹中的某些節點改變時,會得到一個新的虛擬樹。演算法將這兩棵樹(新樹和舊樹)進行比較,找出差異,然後只需要在真實的 DOM 上做出相應的改變。

用JS物件模擬DOM樹

首先,我們需要以某種方式將 DOM 樹儲存在記憶體中。可以使用普通的 JS 物件來做。假設我們有這樣一棵樹:


      
  • item 1
  •   
  • item 2

看起來很簡單,對吧? 如何用JS物件來表示呢?

{ type: ‘ul’, props: { ‘class’: ‘list’ }, children: [
  { type: ‘li’, props: {}, children: [‘item 1’] },
  { type: ‘li’, props: {}, children: [‘item 2’] }
] }

這裡有兩件事需要注意:

  • 用如下物件表示DOM元素
{ type: ‘…’, props: { … }, children: [ … ] }
  • 用普通JS 字串表示DOM 文字節點
##但用這種方式表示內容很多的Dom 樹是相當困難的。這裡來寫一個輔助函數,這樣比較容易理解:

function h(type, props, …children) {
  return { type, props, children };
}
用這個方法重新整理一開始程式碼:

h(‘ul’, { ‘class’: ‘list’ },
  h(‘li’, {}, ‘item 1’),
  h(‘li’, {}, ‘item 2’),
);
這樣看起來簡潔多了,還可以更進一步。這裡使用  JSX,如下:


      
  • item 1
  •   
  • item 2
編譯成:

React.createElement(‘ul’, { className: ‘list’ },
  React.createElement(‘li’, {}, ‘item 1’),
  React.createElement(‘li’, {}, ‘item 2’),
);
是不是看起來有點熟悉?如果能夠用我們剛定義的

h(...) 函數來取代 React.createElement(…),那麼我們也能使用JSX 語法。其實,只需要在原始檔頭加上這麼一句註解:

/** @jsx h */
      
  • item 1
  •   
  • item 2
它實際上告訴Babel ' 嘿,小老弟幫我編譯

JSX 語法,用h( ...) 函數取代React.createElement(…),然後Babel 就開始編譯。 '

綜上所述,我們將DOM寫成這樣:

/** @jsx h */
const a = (
  
        
  • item 1
  •     
  • item 2
  •   
);Babel 會幫我們編譯成這樣的程式碼:

const a = (
  h(‘ul’, { className: ‘list’ },
    h(‘li’, {}, ‘item 1’),
    h(‘li’, {}, ‘item 2’),
  );
);
當函數

“h” 執行時,它將返回普通JS物件-即我們的虛擬DOM:

const a = (
  { type: ‘ul’, props: { className: ‘list’ }, children: [
    { type: ‘li’, props: {}, children: [‘item 1’] },
    { type: ‘li’, props: {}, children: [‘item 2’] }
  ] }
);
從Virtual DOM 映射到真實DOM

#好了,現在我們有了DOM 樹,用普通的JS 物件表示,還有我們自己的結構。這很酷,但我們需要從它創建一個真正的DOM。

首先讓我們做一些假設並聲明一些術語:

    使用以'
  • $ '開頭的變數表示真正的DOM節點(元素,文字節點),因此$parent 將會是一個真實的DOM元素
  • 虛擬DOM 使用名為
  • node 的變數表示
* 就像在React 中一樣,只能有一個根節點-所有其他節點都在其中

那麼,來寫一個函數

createElement(…),它將取得一個虛擬DOM 節點並傳回一個真實的DOM 節點。這裡先不考慮propschildren 屬性:

function createElement(node) {
  if (typeof node === ‘string’) {
    return document.createTextNode(node);
  }
  return document.createElement(node.type);
}
上述方法我也可以建立有兩種節點分別是文字節點和Dom 元素節點,它們是類型為的JS 物件:

{ type: ‘…’, props: { … }, children: [ … ] }
因此,可以在函數

createElement 傳入虛擬文字節點和虛擬元素節點-這是可行的。

現在讓我們考慮子節點——它們中的每一個都是文字節點或元素。所以它們也可以用

createElement(…) 函數來建立。是的,這就像遞歸一樣,所以我們可以為每個元素的子元素呼叫createElement(…),然後使用appendChild() 添加到我們的元素中:

function createElement(node) {
  if (typeof node === ‘string’) {
    return document.createTextNode(node);
  }
  const $el = document.createElement(node.type);
  node.children
    .map(createElement)
    .forEach($el.appendChild.bind($el));
  return $el;
}
哇,看起來不錯。先把節點

props 屬性放到一邊。待會再談。我們不需要它們來理解虛擬DOM的基本概念,因為它們會增加複雜性。

完整程式碼如下:

/** @jsx h */

function h(type, props, ...children) {
  return { type, props, children };
}

function createElement(node) {
  if (typeof node === 'string') {
    return document.createTextNode(node);
  }
  const $el = document.createElement(node.type);
  node.children
    .map(createElement)
    .forEach($el.appendChild.bind($el));
  return $el;
}

const a = (
  
        
  • item 1
  •     
  • item 2
  •   
); const $root = document.getElementById('root'); $root.appendChild(createElement(a));比較兩棵虛擬DOM樹的差異

現在我們可以將虛擬DOM 轉換為真實的DOM,這就需要考慮比較兩棵DOM 樹的差異。基本的,我們需要一個演算法來比較新的樹和舊的樹,它能夠讓我們知道什麼地方改變了,然後相應的去改變真實的 DOM。

怎麼比較 DOM 樹?需要處理下面的情況:

    新增節點,使用
  • appendChild(…) 方法新增節點

如何寫出自己的虛擬DOM?方法介紹

##移除舊節點,使用
    removeChild(…)
  • 方法移除舊的節點

如何寫出自己的虛擬DOM?方法介紹##節點的替換,使用

replaceChild(…)
    方法

#如果節點相同的-就需要有深度比較子節點如何寫出自己的虛擬DOM?方法介紹

编写一个名为 updateElement(…) 的函数,它接受三个参数—— $parentnewNodeoldNode,其中 $parent 是虚拟节点的一个实际 DOM 元素的父元素。现在来看看如何处理上面描述的所有情况。

添加新节点

function updateElement($parent, newNode, oldNode) {
  if (!oldNode) {
    $parent.appendChild(
      createElement(newNode)
    );
  }
}

移除老节点

这里遇到了一个问题——如果在新虚拟树的当前位置没有节点——我们应该从实际的 DOM 中删除它—— 这要如何做呢?

如果我们已知父元素(通过参数传递),我们就能调用 $parent.removeChild(…) 方法把变化映射到真实的 DOM 上。但前提是我们得知道我们的节点在父元素上的索引,我们才能通过 $parent.childNodes[index] 得到该节点的引用。

好的,让我们假设这个索引将被传递给 updateElement 函数(它确实会被传递——稍后将看到)。代码如下:

function updateElement($parent, newNode, oldNode, index = 0) {
  if (!oldNode) {
    $parent.appendChild(
      createElement(newNode)
    );
  } else if (!newNode) {
    $parent.removeChild(
      $parent.childNodes[index]
    );
  }
}

节点的替换

首先,需要编写一个函数来比较两个节点(旧节点和新节点),并告诉节点是否真的发生了变化。还有需要考虑这个节点可以是元素或是文本节点:

function changed(node1, node2) {
  return typeof node1 !== typeof node2 ||
         typeof node1 === ‘string’ && node1 !== node2 ||
         node1.type !== node2.type
}

现在,当前的节点有了 index 属性,就可以很简单的用新节点替换它:

function updateElement($parent, newNode, oldNode, index = 0) {
  if (!oldNode) {
    $parent.appendChild(
      createElement(newNode)
    );
  } else if (!newNode) {
    $parent.removeChild(
      $parent.childNodes[index]
    );
  } else if (changed(newNode, oldNode)) {
    $parent.replaceChild(
      createElement(newNode),
      $parent.childNodes[index]
    );
  }
}

比较子节点

最后,但并非最不重要的是——我们应该遍历这两个节点的每一个子节点并比较它们——实际上为每个节点调用updateElement(…)方法,同样需要用到递归。

  • 当节点是 DOM 元素时我们才需要比较( 文本节点没有子节点 )
  • 我们需要传递当前的节点的引用作为父节点
  • 我们应该一个一个的比较所有的子节点,即使它是 undefined 也没有关系,我们的函数也会正确处理它。
  • 最后是 index,它是子数组中子节点的 index
function updateElement($parent, newNode, oldNode, index = 0) {
  if (!oldNode) {
    $parent.appendChild(
      createElement(newNode)
    );
  } else if (!newNode) {
    $parent.removeChild(
      $parent.childNodes[index]
    );
  } else if (changed(newNode, oldNode)) {
    $parent.replaceChild(
      createElement(newNode),
      $parent.childNodes[index]
    );
  } else if (newNode.type) {
    const newLength = newNode.children.length;
    const oldLength = oldNode.children.length;
    for (let i = 0; i <h2>完整的代码</h2><p><strong>Babel+JSX</strong><br>/<em>* @jsx h </em>/</p><pre class="brush:php;toolbar:false">function h(type, props, ...children) {
  return { type, props, children };
}

function createElement(node) {
  if (typeof node === 'string') {
    return document.createTextNode(node);
  }
  const $el = document.createElement(node.type);
  node.children
    .map(createElement)
    .forEach($el.appendChild.bind($el));
  return $el;
}

function changed(node1, node2) {
  return typeof node1 !== typeof node2 ||
         typeof node1 === 'string' && node1 !== node2 ||
         node1.type !== node2.type
}

function updateElement($parent, newNode, oldNode, index = 0) {
  if (!oldNode) {
    $parent.appendChild(
      createElement(newNode)
    );
  } else if (!newNode) {
    $parent.removeChild(
      $parent.childNodes[index]
    );
  } else if (changed(newNode, oldNode)) {
    $parent.replaceChild(
      createElement(newNode),
      $parent.childNodes[index]
    );
  } else if (newNode.type) {
    const newLength = newNode.children.length;
    const oldLength = oldNode.children.length;
    for (let i = 0; i 
    
  • item 1
  •     
  • item 2
  •    ); const b = (   
          
    • item 1
    •     
    • hello!
    •   
    ); const $root = document.getElementById('root'); const $reload = document.getElementById('reload'); updateElement($root, a); $reload.addEventListener('click', () => {   updateElement($root, b, a); });

    HTML

    <button>RELOAD</button>
    <p></p>

    CSS

    #root {
      border: 1px solid black;
      padding: 10px;
      margin: 30px 0 0 0;
    }

    打开开发者工具,并观察当按下“Reload”按钮时应用的更改。

    如何寫出自己的虛擬DOM?方法介紹

    总结

    现在我们已经编写了虚拟 DOM 实现及了解它的工作原理。作者希望,在阅读了本文之后,对理解虚拟 DOM 如何工作的基本概念以及在幕后如何进行响应有一定的了解。

    然而,这里有一些东西没有突出显示(将在以后的文章中介绍它们):

    • 设置元素属性(props)并进行 diffing/updating
    • 处理事件——向元素中添加事件监听
    • 让虚拟 DOM 与组件一起工作,比如React
    • 获取对实际DOM节点的引用
    • 使用带有库的虚拟 DOM,这些库可以直接改变真实的 DOM,比如 jQuery 及其插件

    原文地址:https://medium.com/@deathmood/how-to-write-your-own-virtual-dom-ee74acc13060

    作者:deathmood

    为了保证的可读性,本文采用意译而非直译。

    更多编程相关知识,请访问:编程入门!!

    以上是如何寫出自己的虛擬DOM?方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除