This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
Question:
Why did React launch JSX?
How to create a virtual DOM?
Next we create a small example of wrapping Hello React in a span tag using JS and JSX, respectively
1. JSX creates the virtual DOM
import React from 'react';
import ReactDOM from 'react-dom';
const VDOM = (
<h1>
<span>
Hello React
</span>
</h1> )
ReactDOM.render(VDOM,document.getElementById('root'))
Copy the code
This way to write with our usual label is not almost the same. Browsers can’t parse this, so why can we use that? It is converted by Babel. So what kind of structure does that translate into? In fact, it still translates to the following js creation syntax.
2. Creating a virtual DOM with JS (almost no use)
- How do I create a DOM?
document.createElement()
Copy the code
- How do I create a virtual DOM?
Creating a DOM requires a Document object, and creating a virtual DOM requires a React object
React.createElement()
Copy the code
Three parameters :(tag name, tag attribute, tag content)
Let’s render the text first
import React from 'react';
import ReactDOM from 'react-dom';
/** * (tag name, tag attribute, tag content) */
const VDOM = React.createElement('h1', {id:'title'},'Hello React')
ReactDOM.render(VDOM,document.getElementById('root'))
Copy the code
So, if you want to put a span tag around the Hello React text can you just put it in quotes?
const VDOM = React.createElement('h1', {id:'title'},'<span>Hello React</span>')
Copy the code
Obviously notWe need to create the virtual DOM of span with React again, because we don’t need properties so we pass {} as the second argument.
const VDOM = React.createElement('h1', {id:'title'},React.createElement('span', {},'Hello React'))
Copy the code
So let’s think about what we need to do if we want to create four levels of nested tags. This is where the JSX syntax comes in.
3. Virtual DOM and real DOM
3.1 What is the Virtual DOM?
Let’s print out the virtual DOM at the end
const VDOM = <h1><span>Hello React</span></h1>
ReactDOM.render(VDOM,document.getElementById('root'))
console.log("VDOM",VDOM)
Copy the code
You can see it’s an object
3.2 real DOM
ReactDOM.render(VDOM,document.getElementById('root'))
const TDOM = document.getElementById('root');
console.log("VDOM",VDOM)
console.log("TDOM",TDOM)
Copy the code
You print out a bunch of labels, and you don’t see what attributes it hasSo, let’s put a breakpoint debugger underneath it that’s a property of the real DOM, a lot of it.
3.3 About the Virtual DOM
- Objects that are essentially of type Object (general objects)
- Let’s compare the real DOM. The virtual DOM is “light” and the real DOM is “heavy.” Because the virtual DOM is used internally in React it doesn’t require as many attributes.
- The virtual DOM will eventually be transformed into the real DOM, which will eventually be rendered on the page.