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(1) #40

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

vdom(1) #40

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

Comments

@zwhu
Copy link
Owner

zwhu commented Apr 10, 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, space = '') {
        let str = ''
        if (node.children)
            str = (`<${node.tag}${renderProps(node.props)}>\n${node.children.map(_ => dfs(_, '  ') + '\n').join('')}</${node.tag}>`)
        else if (typeof node === 'string')
            str = node
        else
            str = `<${node.tag}${renderProps(node.props)}/>`

        return str.split('\n').map(_ => space + _).join('\n')
    }
    return dfs(root)
}

function renderProps(props) {
    if (!props) return ''
    return Object.keys(props).reduce((str, key) => `${str} ${key}="${props[key]}"`, '')
}

console.log(render(vdom))
<div style="display:none">
  <a id="1" href="http://test.com" target="_blank">
    click!
  </a>
  this is text!!!
  <div class="class1 class2" data-attr="hello">
    haha
    <br/>
  </div>
  <br/>
</div>
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