const element = <h1title="foo">hello</h1> const container = document.getELementById("root") ReactDOM.render(element,container)
JSX -> Babel(replace the code inside the tags with a call to createElement, passing the tag name, the props and the children as parameters.) -> ReactDOM.render -> DOM
The children array could also contain primitive values like strings or numbers. So we’ll wrap everything that isn’t an object inside its own element and create a special type for them: TEXT_ELEMENT.
But we still want to use JSX here. How do we tell babel to use Didact’s createElement instead of React’s? If we have a comment like this one, when babel transpiles the JSX it will use the function we define.
3、Step2: The render Function In this section, we will introduce the render function, which will take the element we created and render it to the DOM.
1 2 3
functionrender(element, container){ // TODO create dom nodes }
We start by creating the DOM node using the element type, and then append the new node to the container.
1 2 3 4 5 6 7 8 9
functionrender(element, container){ // We start by creating the DOM node using the element type, and then append the new node to the container. const dom = document.createElement(element.type); // We recursively do the same for each child. element.props.children.forEach(child => { render(child, dom); }); container.appendChild(dom); }
We also need to handle text elements, if the element type is TEXT_ELEMENT we create a text node instead of a regular node.
1 2 3 4 5 6 7 8 9 10 11 12 13
functionrender(element,container){ const dom = element.type === "TEXT_ELEMENT" ? document.createTextNode("") : document.createElement(element.type); // We recursively do the same for each child. element.props.children.forEach(child => { render(child, dom); }); container.appendChild(dom); }
The last thing we need to do here is assign the element props to the node.