The rendering principle of reactdom.render
In the React project, we can write template structures directly in functions/components because Babel translates these templates to react. CreateElemen (config). This is why we do not call React in each component. But the reason why react is introduced.
/ / for
import React from 'react';
import ReactDOM from 'react-dom';
let h = React.createElement(
'div', {className:'box'.style: {fontSize:'30px'.color:'green'}},'First son',
React.createElement('h2', {style: {color:'red'.textAlign: 'center'}},'Second son'));let p = <div className='box' style={{fontSize:'30px', color:'green'}} >First son<h2 style={{color:'red',textAlign: 'center'}} >Second son</h2>
</div>
ReactDOM.render(<>
{h}
{p}
</>.document.getElementById('root'));
// p and H render the same page
Copy the code
Render result:
React.createElement and reactdom. render are simple implementations
let React = {
createElement(type, attrs,... children){
// Step 1: Create a real DOM
let el = document.createElement(type);
// Step 2: process inline attributes
let keys = Object.keys(attrs);
for(let i=0; i<keys.length; i++) {
let key = keys[i];
switch(key) {
case 'className':
el.setAttribute('class', attrs[key]);
break;
case 'htmlFor':
el.setAttribute('for', attrs[key]);
break;
case 'style':
let str = ' '
Object.keys(attrs.style).forEach(item= >{
str += `${React.changeStr(item)}:${attrs.style[item]}; `
});
el.setAttribute('style', str);
break;
default: el.setAttribute(key, attrs[key]); }}// Step 3: Process the descendant element
children.forEach(child= >{
if(typeof child === 'string') {
el.appendChild(document.createTextNode(child))
}else {
// console.log(child, 'else')
el.appendChild(child)
}
})
// Finally, return the actual DOM created
return el;
},
changeStr(str){
// Assist function: the purpose is to convert the camel-named attribute to a string name
// For example: fontSize -> font size
return str.replace(/[A-Z]/g.b= >{
return The '-' + b.toLowerCase();
}).replace(/ ^ - /.' ')}};let ReactDOM = {
render(el, container){
// el is the real DOM after react. createElement
// Insert the converted real DOM into the containercontainer.appendChild(el); }}let h = React.createElement(
'div', {className:'box'.style: {fontSize:'30px'.color:'green'}},'First son',
React.createElement('h2', {style: {color:'red'.textAlign: 'center'}},'Second son')); ReactDOM.render(h,document.getElementById('root'));
Copy the code