// 最简单的renden实现
function ReactElement(type,props) {
this.type=type
this.props=props
}
function createElement(type,props,...children) {
if(children.length==1){
children=children[0]
}
return new ReactElement(type,{
...props,
children:children
})
}
let myRender=(obj,container)=>{
let {type,props}=obj
let ele=document.createElement(type);
for(let key in props){
if(key=='children'){
// 数组
if(typeof props[key]=='object'){
props[key].forEach(item=>{
if(typeof item=='object'){
myRender(item,ele)
}
else{
ele.appendChild(document.createTextNode(item))
}
})
}
// 一个
else{
ele.appendChild(document.createTextNode(props[key]))
}
}
else if(key=='className'){
ele.setAttribute('class',props[key])
}
else{
ele.setAttribute(key,props[key])
}
}
container.appendChild(ele)
}
console.log(createElement(
'h1',
{className:'red'},
'刘,',
createElement(
'span',
{id:'handsome'},
'帅哥',
)
)
)
myRender(createElement(
'h1',
{className:'red'},
'刘,',
createElement(
'span',
{id:'handsome'},
'帅哥',
)
), document.getElementById('root'));
1.2 最简单的renden实现
最新推荐文章于 2022-01-24 20:18:05 发布