// react/src/ReactElement.js
export function createElement(type, config, children) {
// 一些处理...
return ReactElement(
type,
key,
ref,
self,
source,
ReactCurrentOwner.current,
props,
);
}
const ReactElement = function(type, key, ref, self, source, owner, props) {
const element = {
// This tag allows us to uniquely identify this as a React Element
$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner,
};
return element;
};
从上面代码可以看出createElement
最后返回了ReactElement
对象,createElement
传入了三个参数:
- type
- config
- children
type:指的是ReactElement
的类型,有字符串、class类型、funtion类型、Fragment等等;
config:就是传进来的绑在当前节点或者组件上的所有属性,在源码里可以看到config里的key, ref会被单独拎出来放在ReactElement
上;
children:可能一个或者多个,最后children会经过处理,在ReactElement
的props.children返回,分两种情况:单个或者数组的形式。
ReactElement
只是一个用来承载信息的容器,它会告诉后续的操作这个节点的以下信息:
type
类型,用于判断如何创建节点;key
和ref
这些特殊信息;props
新的属性内容;$$typeof
用于确定是否属于ReactElement
;
这些信息对于后期构建应用的树结构是非常重要的,而React通过提供这种类型的数据,来脱离平台的。