最近,我研究了Facebook的React框架。它使用了一个叫做“虚拟DOM”的概念,我并不真正理解这个概念。
什么是虚拟DOM?它的优点是什么?
最近,我研究了Facebook的React框架。它使用了一个叫做“虚拟DOM”的概念,我并不真正理解这个概念。
什么是虚拟DOM?它的优点是什么?
当前回答
这是一个简洁的概念:不直接操作DOM(容易出错并且依赖于可变状态),而是输出一个名为Virtual DOM的值。然后,虚拟DOM与DOM的当前状态进行区分,这会生成一个DOM操作列表,使当前DOM看起来像新DOM。这些操作在批量中快速应用。
从这里拍的。
其他回答
虚拟DOM是HTML DOM的抽象,它根据状态变化选择性地呈现节点的子树。它尽可能少地进行DOM操作,以使组件保持最新状态。
让我们把这件事理清楚。 React(或其他库)是javascript上的一个“层”。
没有所谓的虚拟王国, 有独立的dom。
让我用简单的javascript解释一下:
let vDom = {}; // this is a object that will be used to hold the elements
let d = document.createElement('div');
d.innerHTML = 'hi, i am a new div';
vDom['newDiv'] = d;
在这一点上,我们已经创建了一个Div没有显示在dom,因为它 尚未附上
但是我们可以访问它,添加属性,值,改变等等。
一旦我们调用:(对于ex,将它添加到body)
document.body.appendChild(vDom['newDiv'])
然后我们会看到它;
for one how saw javascript libs come and go , i suggest to any one
to do one simple thing : master JAVAscript, not layers :)
这是对ReactJS中经常提到的Virtual DOM的简要描述和重申。
The DOM (Document Object Model) is an abstraction of structured text, which means it is made of HTML code and css. These HTML elements become nodes in the DOM. There are limitations to the previous methods of manipulating the DOM. Virtual DOM is an abstraction of the literal HTML DOM created well before React was created or used, but for our purposes we will use it in concert with ReactJS. The Virtual DOM is lightweight and detached from the DOM implementation in the browser. The Virtual DOM is essentially a screenshot (or copy) of the DOM at a given time. A way to look at it from a developers perspective is the DOM is the production environment and the Virtual DOM is the local (dev) environment. Each time the data changes in a React app a new Virtual DOM representation of the user interface is created.
为了在ReactJS中创建静态组件,最基本的方法是:
必须从呈现方法返回代码。 您必须将每个类转换为className,因为class是JavaScript中的保留字。 除了更大的变化之外,两个DOM之间还有一些小差异,包括虚拟DOM中出现而HTML DOM中没有出现的三个属性(key、ref和dangerlysetinnerhtml)。
在使用Virtual DOM时,需要理解的一件重要事情是ReactElement和ReactComponent之间的区别。
ReactElement
ReactElement是DOM元素的轻量级、无状态、不可变的虚拟表示。 ReactElement -这是React中的主要类型,位于Virtual DOM中。 ReactElements可以被渲染成HTML DOM var root = React.createElement('div'); ReactDOM。呈现(根,. getelementbyid(例子)); JSX将HTML标记编译为ReactElements Var root = <div/>; ReactDOM。呈现(根,. getelementbyid(例子));
ReactComponent
ReactComponent——ReactComponent是有状态的组件。 反应。createClass被认为是一个ReactComponent。 每当状态改变时,组件都会被重新呈现。
每当ReactComponent发生状态变化时,我们希望对HTML DOM的更改尽可能少,这样ReactComponent就可以转换为ReactElement,然后ReactElement可以插入到Virtual DOM中,快速方便地进行比较和更新。
当React知道diff时,它会被转换为低级代码(HTML DOM),并在DOM中执行。
什么是虚拟DOM?
虚拟DOM是React组件在对页面进行任何更改之前生成的真实DOM元素的内存表示。
它是发生在渲染函数被调用和元素在屏幕上显示之间的一个步骤。
组件的渲染方法返回一些标记,但还不是最终的HTML。它是将成为真正元素的内存表示(这是第一步),然后输出将被转换为真正的HTML,这是在浏览器中显示的内容(这是第2步)。
那么,为什么要进行所有这些操作来生成虚拟DOM呢? 简单的回答——这就是让反应更快的原因。它通过虚拟DOM差分来做到这一点。比较两个虚拟树(旧的和新的),只对真正的DOM进行必要的更改。
来源自我的博客Intro To React #2
虚拟Dom是创建Dom的一个副本。虚拟dom与dom比较,虚拟dom只更新dom中发生变化的部分。它没有渲染整个dom它只是改变了dom中dom的更新部分。这是非常耗时的,从这个功能,我们的应用程序工作得很快。