1. Realize the React
- the first to use webpack or parcel (using document: [https://zh.parceljs.org/getting_started.html] ()) to build environment - at this time we are new the React under the SRC directory. Js file, manually createCopy the code
let React = {}
React.createElement = (type,attrs,... children) => {if(!type) {
return
}
return {
type,
attrs,
children
}
}
exportDefault ReacttypeAttrs refers to the tag type, attrs refers to the value, and children is a child such as <div id="app">
<span>hello react</span>
</div>
Copy the code
Now we can add React to index.js
2. Implement the React – DOM
The next step is to render the virtual DOM by creating a new react-dom.js file in the SRC directoryCopy the code
function ReactDOM(vnode, contanier) {
let element;
const { type, attrs, children } = vnode; //1. Check whether the DOM is a text node, if yes, create a text node, otherwise create a DOM nodeif (typeof vnode === "string") {
element = document.createTextNode(vnode);
} else {
element = document.createElement(type); } //2. Insert attrs into the DOMsetAttribute(element, attrs); Contanier.appendchild (element); // If there are any children, render them into each element one by oneif(children && children.length) { children.forEach((node) => { ReactDOM(node, element); }); }} // Implement onesetAttribute method 1. Check whether a value exists. If yes, go to the next stepreturn2. The values are divided into three types, one is normal, such as ID, the other is className, and the other is stylefunction setAttribute(element, attrs) {
if(! element || ! attrs) {return;
}
Object.keys(attrs).forEach((attr) => {
const value = attrs[attr];
if (attr === "className") {
element.setAttribute("class", value);
} else if (attr === "style") {
if (typeof value === "string") {
element.style.cssText = value;
} else if (isObject(value)) {
let str = "";
Object.keys(value).forEach((ele) => {
str += ele + ":" + value[ele] + ";"; element.style.cssText = str; }); }}else{ element.setAttribute(attr, value); }}); } // Determine if it is an objectfunction isObject(obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
}
export default ReactDOM;
Copy the code
At this point, act1.0 is basically implemented, so let’s use it in index.js
import React from './src/react'
import ReactDOM from './src/react_-dom'
ReactDOM(
<div id="app" className="app-class">
oioioio
<div
id="span"
className="span-class"
style={{ color: "#f00", width: "100px" }}
>
span
</div>
</div>,
document.getElementById("root"));Copy the code
Okay, if this feels easy, give it a try, and we’ll update series 2 to add life cycles and events