The react virtual DOM is converted to the real DOM:

Const el = require('./element.js'); const ul = el('ul', {id: 'list'}, [ el('li', {class: 'item'}, ['Item 1']), el('li', {class: 'item'}, ['Item 2']), el('li', {class: 'item'}, ['Item 3']) ]) const ulRoot = ul.render(); document.body.appendChild(ulRoot); Code output:  <ul id='list'> <li class='item'>Item 1</li> <li class='item'>Item 2</li> <li class='item'>Item 3</li> </ul> Code element.js?Copy the code

Here are the answers:

<! -- html --> <! DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <script src="script.js"></script> </body> </html>Copy the code
//script.js
var el = require("./element.js")
window.onload = function(){
const ul = el('ul', {id: 'list'}, [
  el('li', {class: 'item'}, ['Item 1']),
  el('li', {class: 'item'}, ['Item 2']),
  el('li', {class: 'item'}, ['Item 3'])
])
const ulRoot = ul.render();
document.body.appendChild(ulRoot);
}
Copy the code
//element.js function Element(tagName,props,children){ this.tagName = tagName this.props = props this.children = Prototype = function(){var el = document.createElement(this.prototype) var props = function(){var el = document.createElement(this.prototype) This. Props for(propName in props){var propVal = props. PropName el.setAttribute(propName,propVal) // Add attributes to DOM elements} var children = this.children || [] children.forEach(child=>{ el.appendChild((child instanceof Element)? child.render():document.createTextNode(child)) }) return el } module.exports = function(tagName,props,children){ return new Element(tagName,props,children) }Copy the code

Ideas: The element.js export function is an instance generator that can call its own render method to generate new DOM elements. The element.js export function is an object instance generator that can obtain instances by passing in corresponding attributes. So there should also be a constructor in element.js that takes those attributes and has the Render method that uses them to generate DOM elements. Here’s how to write the element.prototype. render method. Create the DOM element EL using document.createElement(this.tagName) and add attributes to the element using the el.setAttribute(propName,propVal) loop. AppendChild ((child instanceof Element)? Child.render ():document.createTextNode(child)) adds a child element to el.children. If it’s element, call the render function recursively. Calling the DOM API multiple times requires a certain degree of proficiency.