The goal of this section is to implement reactdom.render, which only cares about adding content to the DOM and then dealing with updating and deleting content;
React /react-dom.js;
Once you have your virtual DOM data structure, the next step is to convert it into a real DOM structure and render it on the page. There are basically four steps:
- Create different types of nodes
- Adding properties props
- Iterate over children, recursively calling Render
- Append the generated node to the root node
Specific implementation steps:
1. Create the react-dom.js file
Create a DOM node and add the new node to the container
// react/react-dom.js
/** * Convert the virtual DOM to the real DOM and add it to the container *@param {element} Virtual DOM *@param {container} Real DOM * /
function render(element, container) {
const dom = document.createElement(element.type)
container.appendChild(dom)
}
Copy the code
3. Add each element. Props. Children to the DOM node
element.props.children.forEach(child= >
render(child, dom)
)
Copy the code
4. Handle text nodes
const dom =
element.type == "TEXT_ELEMENT"
? document.createTextNode("")
: document.createElement(element.type)
Copy the code
5. Bind attributes to nodes
// Bind attributes to the node
const isProperty = key= >key ! = ="children"
Object.keys(element.props)
.filter(isProperty)
.forEach(name= > {
dom[name] = element.props[name]
})
Copy the code
6, test,
JSX to DOM library: JSX to DOM
6.1 Introducing the render method into the react/index.js file
6.2 Adding the React. Render method
Add the React. Render method to the SRC /index.js file:
// src/index
import React from '.. /react';
const element = (
<div id="foo">
<a>bar</a>
<b />
</div>
)
React.render(element, document.getElementById('root'))
Copy the code
6.3 Modifying the WebPack Configuration
Add the index.html file to the SRC directory and add a node with the DOM attribute id:
Modify the WebPack configuration by adding the HTML template:
6.4 run
Run the NPM run start command to start the system, and you can see that the result is displayed successfully:
7,
Use the flow chart to briefly summarize sections 2 and 3:
8. This section code
Code address: gitee.com/linhexs/rea…
9. Relevance
1. CreateElement implementation: juejin.cn/post/702030…