实现createElement函数

CreateElement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// createElement.js
function createElement(type, props, ...children) {
return {
type,
props: {
...props,
children: children.map(child => {
return (typeof child === 'object') ? child : createTextElement(child)
})
}
}
}

// text 文本节点
function createTextElement(text) {
return {
type: 'TEXT_ELEMENT',
props: {
nodeValue: text,
children: [],
},
}
}

export default createElement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// main.js
import { createElement, render } from 'micro-react'

// 创建 dom 节点
const element = createElement({
type: 'h1',
{ class: 'custom', id: 1, style: 'background: yellow'},
'Hello Word',
createElement('h2', null, 'Effort')
})

// 渲染 dom
const container = document.querySelector('#root')
render(element, container)