跳到主要内容

Virtual-DOM

当 JSX 经 babel 转义为React.createElement(component, props, ...children)

概念:

  • React.createElement返回的结果就是虚拟 DOM
  • 虚拟 DOM 是描述真实 DOM 的 js 对象

经过转换后,打印出来的是一个 JS 对象详细的描述 JSX

const element = <div id='app' className='name'>地球</div>
console.log(element)
{
$$typeof: Symbol(react.element)
key: null
props: {id: 'app', className: 'name', children: '地球'}
ref: null
type: "div"
_owner: null
_store: {validated: false}
_self: null
}

createElement

// packages\react\src\ReactElement.js
const RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true,
};
function createElement(type, config, children) {
let propName;
//提取保留名称
const props = {};
let key = null;
let ref = null;
if (config) {
if (config.ref) {
ref = config.ref;
}
if (config.key) {
key = '' + config.key;
}
for (propName in config) {
if (!RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
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;
}
return {
$$typeof: REACT_ELEMENT_TYPE,
type,
ref,
key,
props,
};
}