我们来实现一下createElement这个方法。
根据之前的文章,我们也介绍了。通过调用React.createElement这个方法,最终返回的是一个包含type和props属性的对象。
我们需要接受一些参数,第一个就是要创建element的类型。第二个为这个这个element属性对象,之后就是这个element的子元素。1
2
3
4
5
6
7
8
9function createElement(type, props, ...children) {
return {
type,
props: {
...props,
children
}
}
}
我们使用解构参数的形式,来获取children参数。这样能保证children永远是一个数组。1
2
3
4
5
6
7我们调用
createElement("div", null, a, b)
返回
{
"type": "div",
"props": { "children": [a, b] }
}
有可能在children数组中包含基本数据类型,而并非一个对象,如string或者number。我们需要将这些转换成一个对象。我们改写一下上面的代码。
function createElement(type, props, ...children) {
return {
type,
props: {
...props,
children: children.map(child => {
return typeof child === 'object'
? child
: createTextElement(child)
})
}
}
}
function createTextElement(text) {
return {
type: 'TEXT_ELEMENT',
props: {
nodeValue: text,
children: [],
},
}
}
至此我们就实现了createElement方法。