console
const REACT_ELEMENT_TYPE = Symbol('react.element')
function ReactElement(type, key, ref, props) {
const element = {
$$type: REACT_ELEMENT_TYPE,
type,
key,
ref,
props
}
return element
}
function createElement(type, config, ...children) {
const {
key,
ref,
...resProps
} = config || {}
const props = {
...resProps,
children
}
return ReactElement(
type,
key,
type,
props
)
}
const React = {
createElement
}
function Child(props){
const {name} = props
return (
<div>{name}</div>
)
}
function App() {
return (
<p>
<div key='abcd' ref='efg'>Hello World!</div>
<a href='http://www.baidu.com' target='_blank'>baidu</a>
<Child name="name"/>
</p>
)
}
function render(dom, container) {
let node
if (typeof dom === 'string') {
node = document.createTextNode(dom)
} else {
const { type, props = {} } = dom
const { children = [], ...resProps } = props
if (typeof type === 'function') {
let newDom = type(resProps)
console.log(newDom)
return render(newDom, container)
}
node = document.createElement(type)
Object.entries(resProps).forEach(([key,value])=>{
node.setAttribute(key,value)
})
children.map((child) => render(child, node))
}
container.appendChild(node)
}
render(<App />, document.getElementById('root'))
<div id="root"/>