What is Virtual DOM?

前端 未结 12 700
遥遥无期
遥遥无期 2020-11-28 01:39

Recently, I looked at Facebook\'s React framework. It uses a concept called \"the Virtual DOM,\" which I didn\'t really understand.

What is the Virtual DOM? What are

12条回答
  •  一向
    一向 (楼主)
    2020-11-28 02:20

    This is a brief description and reiteration of the Virtual DOM often mentioned alongside ReactJS.

    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.

    The most basic method needed in order to create a static component in ReactJS are:

    You must return code from the render method. You must convert every class to className since class is reserved word in JavaScript. Aside from the more major changes there are minor differences between the two DOMs including three attributes appearing in the Virtual DOM but not in the HTML DOM (key, ref and dangerouslySetInnerHTML).

    An important thing to understand when working with the Virtual DOM is the difference between ReactElement and ReactComponent.

    ReactElement

    • A ReactElement is a light, stateless, immutable, virtual representation of a DOM Element.
    • ReactElement - This is the primary type in React and resides in the Virtual DOM.
    • ReactElements can be rendered into HTML DOM

      var root = React.createElement('div'); ReactDOM.render(root, document.getElementById('example'));

    • JSX compiles HTML tags into ReactElements

      var root =

      ; ReactDOM.render(root, document.getElementById('example'));

    ReactComponent

    • ReactComponent - ReactComponent's are stateful components.
    • React.createClass is considered a ReactComponent.
    • Whenever state changes the component is rerendered.

    Whenever a ReactComponent has a state change, we want as little change to the HTML DOM as possible so ReactComponent is converted to the ReactElement which can then be inserted to the Virtual DOM, compared and updated fast and easily.

    When React knows the diff - it's converted to the low-level (HTML DOM) code, which is executed in the DOM.

提交回复
热议问题