四、实现简易的React.createElement() 和 R
2020-03-21 本文已影响0人
自己写了自己看
1、React.createElement()
export function createElement(type, props, ...childs) {
let obj = {};
obj.type = type;
obj.props = props || {};
if (childs.length > 0) {
obj.props.children = childs.length === 1 ? childs[0] : childs;
}
}
2、React.render()
export function render(jsxObj, container, callback) {
let { type, props } = jsxObj;
let element = document.createElement(type);
for (const key in props) {
if (!props.hasOwnProperty(key)) break; // 不是props自身的不添加
// className
if (props[key] === 'className') {
element.className = props[key];
continue;
}
// style
if (props[key] === 'style') {
let sty = props[key];
for (const attr in sty) {
if (!props.hasOwnProperty(attr)) break;
element['style'][attr] = sty[attr];
}
}
// children
if (key === 'children') {
let children = props['children']
children = Array.isArray(children) ? children : [children];
children.forEach(item => {
if (typeof item === 'string') {
element.appendChild(document.createTextNode(item));
return;
}
// 递归
render(item, element);
});
continue;
}
element.setAttribute(key, props[key]);
}
container.appendChild(element);
callback && callback();
}