Open zwhu opened 6 years ago
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>