function render(element,container){
if(typeof element == 'string' || typeof element == 'number'){ //如果element是一个普通的字符串或者数字,就创建文本节点并添加进去
container.appendChild(document.createTextNode(element));
}
//这里是因为在执行React.createElement()方法之后返回的element元素包含了type、props属性
let type = element.type; // 获取react元素的类型
let props = element.props; //获取react元素的属性
if(typeof type === 'function'){
let renderedElement;
if(type.isReactComponent){ //说明是一个类组件
let inst = new type(props);
renderedElement = inst.render(); //调用class的render方法返回react元素
}else{ //函数组件
renderedElement = type(props);
}
type = renderedElement.type;
props = renderedElement.props;
}
//创建react元素
let domElement = document.createElement(type);
for(let propName in props){
if(propName == 'className'){
domElement.className = props[propName];
}else if(propName == 'style'){
let styleObj = props[propName];
for(let attr in styleObj){
domElement.style[attr] = styleObj[attr];
}
}else if(/^on[A-Z]/.test(propName)){ //处理react事件
domElement[propName.toLowerCase()] = props[propName];
}else if(propName == 'children'){
let children = Array.isArray(props.children) ? props.children : [props.children];
children.forEach(child => render(child,domElement));
}
}
container.appendChild(domElement);
}
export default {
render
}
网友评论