一:React.createElement
1.react 中的 jsx 代码会被bable编译成React.createElement, 所以在写 jsx 代码的时候 要引入React,否则会报错
<div className="first">第一次学习源码丫~</div>
//像这样的jsx会被编译成
React.createElement('div', {
className: 'first'
}, '第一次学习源码丫~')
createElement是创建并返回一个给定类型的ReactElement 元素,它有三个参数,其中type是是必须的,config和children是可选的。
type:可以是html的tagName,也可以是ReactClass
config:该标签的属性,这些属性可以用过this.props.xxx来取到
children:该元素的子节点
//源码如下:
function createElement(type, config, children) {
var propName = void 0; //void 0 返回的就是undefined
// Reserved names are extracted 提取保留名称
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
//对该标签属性的一些处理,如果属性不为空,就把特殊的属性取出来 ref, key,__self, __source
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
}
if (hasValidKey(config)) {
key = '' + config.key; //转为string类型
}
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 (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { //hasOwnProperty 判断括号中的属性在不在自身中,不会检查原型链
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto the newly allocated props object.(children 可以是多个参数,这些参数被转移到新分配的props对象上)
//如果children是一个,就直接赋值给props.children
//如果不是一个,就吧它放在数组里 赋值给props.children
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
{
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
}
// Resolve default props 处理默认值defaultProps
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
{
if (key || ref) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
createElement的流程图解: