前言
前面已经完成 createElement 源码实现,本文将继续实现同步渲染 render 方法,用于渲染 ReactElement 对象为真实 dom。
渲染流程
- 编写的 jsx 语法,本质是 createElement 方法创建 json 对象;
- 通过 render 方法将第一步中生成 json 对象转成真实 dom,然后在 appendChild 容器 dom 里面;
源码实现
function render(element, container) {
const { type, props } = element;
const dom = type === 'TEXT_ELEMENT' ?
document.createTextNode('') :
document.createElement(type);
Object.keys(props).forEach(key => {
if (key !== 'children') {
dom[key] = props[key];
}
});
const { children = [] } = props;
children.forEach(child => {
render(child, dom);
})
container.appendChild(dom);
}
export {
render
}
存在的问题
递归渲染,递归树结构一旦开始,不能中断,阻塞主线程。