kangduu / front-end-camps

Front-end learning, interviews, question banks, algorithm camps.
https://kangduu.github.io/front-end-camps
MIT License
2 stars 0 forks source link

快速手撸一个虚拟DOM #31

Open autonomly opened 7 months ago

autonomly commented 7 months ago
export default function h(tagName, { props = {}, children = {} }) {
    const virtualElement = Object.create(null);
    return  Object.assign(virtualElement, {
        tagName,
        props,
        children
    })
}

export function render(virtualNode) {
    if (typeof virtualNode === 'string') {
        return document.createTextNode(virtualNode);
    }
    const $element = document.createElement(virtualNode.tagName);
    for (const [ key, value ] of Object.entries(virtualNode.props)) {
        $element.setAttribute(key, value);
    }
    if (virtualNode.children && virtualNode.children.length > 0) {
        virtualNode.forEach((childNode) => {
            $element.appendChild(render(childNode));
        })
    }
}

export function appMount(node, target) {
    if (!node instanceof HTMLElement) {
        throw new Error('挂载对象不是一个DOM节点!');
        return null;
    }
    return target.appendChild(appMount);
}