# react element
# jsx到javaScript的转换
function Comp = () => {
return ...
}
<div className={danger} key='1'>
1111
<span>2222</span>
</div >
}
<Comp />
在react中使用jsx语法的时候会用Babel的jsx编译器转成react.createElement方法,参数就是这个对象
react.createElement('div',
{className: 'danger', key: '1'}
'111',
react.createElement('span', null, '2222')),
)
react.createElement(Comp, null)
react根据组件首字母是否大些来判断当前组件是原生组件或者自定义组件,传参方式不同。原生组件为字符串,自定义组件为一个变量
# react.createElement
export function createElement(type, config, children) {
let propName;
// Reserved names are extracted
const props = {};
let key = null;
let ref = null;
let self = null;
let source = null;
// 判断是否传入配置,比如 <div className='11'></div> 中的 className 会被解析到配置中
if (config != null) {
// 验证 ref 和 key,只在开发环境下
if (hasValidRef(config)) {
ref = config.ref;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
// 赋值操作
// self 呢就是为了以后正确获取 this
// source 基本来说没啥用,内部有一些 filename, line number 这种
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
// 遍历配置,把内建的几个属性剔除后丢到 props 中
for (propName in config) {
if (
//lookhere
hasOwnProperty.call(config, propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)
) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
// 处理 children 的几个操作
const childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
const childArray = Array(childrenLength);
for (let i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// Resolve default props
// 判断是否有给组件设置 defaultProps,有的话判断是否有给 props 赋值,只有当值为
// undefined 时,才会设置默认值
if (type && type.defaultProps) {
const defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
return ReactElement(
type,
key,
ref,
self,
source,
ReactCurrentOwner.current,
props,
);
}
createElement所做的事情如下
1、处理config即我们所传递的ref、id、className等
2、处理子元素
3、处理默认值
经过上述处理后会得到几个值type、key等这些值,得到这几个值后会把这些值作为参数传递给 ReactElement方法
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;
};
ReactElement方法相当于一个工厂函数返回了一个react element元素