React.createElement
ts
export function createElement(type, props, ...children) {
return {
type,
props,
children: children.map((child) =>
typeof child === 'object' ? child : createTextElement(child)
),
};
}
function createTextElement(text) {
return {
type: 'TEXT_ELEMENT',
props: {
nodeValue: text,
},
};
}
render
ts
interface Element {
type: 'TEXT_ELEMENT' | keyof HTMLElementTagNameMap;
props?: any;
children?: any[];
}
export function render(element: Element, parentNode) {
const { type, props, children = [] } = element;
const node = type === 'TEXT_ELEMENT' ? document.createTextNode('') : document.createElement(type);
for (const key in props) {
node[key] = props[key];
}
children?.forEach((child) => render(child, node));
parentNode.appendChild(node);
}