Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vdom(2) #41

Open
zwhu opened this issue Apr 11, 2018 · 0 comments
Open

vdom(2) #41

zwhu opened this issue Apr 11, 2018 · 0 comments
Labels

Comments

@zwhu
Copy link
Owner

zwhu commented Apr 11, 2018

let vdom = {
    tag: 'div',
    props: {
        style: 'display:none'
    },
    children: [{
        tag: 'a',
        props: {
            id: '1',
            href: 'http://test.com',
            target: '_blank'
        },
        children: ["click!"]
    }, 'this is text!!!', {
        tag: 'div',
        props: {
            class: 'class1 class2',
            'data-attr': 'hello'
        },
        children: ['haha', {
            tag: 'br'
        }]
    }, {
        tag: 'br'
    }]
}

function render(root) {

    function dfs(node) {
        let element
        if (node.tag) {
            element = createElement(node.tag, node.props)
            node.children && node.children.map(dfs).forEach(element.appendChild)
        } else if (typeof node === 'string')
            element = createTextNode(node)

        return element
    }
    return dfs(root)
}

function createElement(tag, props = {}) {
    const element = document.createElement(tag)
    Object.keys(props).forEach((key) => { element.setAttribute(key, props[key]) })
    return element
}

function createTextNode(text) {
    return document.createTextNode(text)
}

console.log(render(vdom))

运行结果如下:

运行结果

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant