一、前言
【在正式学习该文章前,可以先学习VirtualDOM系列文章:VirtualDOM】
上篇文章(从 JSX 到 React.createElement ),以及 Babel 的 babel-standalone.js 分析,告诉我们,无论是手动调用,还是由babel来调用,在真正调用 ReactDOM.render 渲染之前,都会去调用 React.createElement 方法,然后再塞到 div.container 中,最后才渲染。
二、React.createElement
[代码所在文件:react/src/ReactElement.s]
const React = {
......
createElement: __DEV__ ? createElementWithValidation : createElement,
......
};
在React.js中,如果当前运行的环境是DEV,则会先调用 createElementWithValidation ,对传入的 type 进行检查,然后再调用 createElement ,而生产环境则是直接调用 createElement ;
三、再谈JSX到React.createElement
当我们有很多嵌套HTML标签,再被加载运行时,babel会将整个JSX都transform为React.createElement,且保持嵌套顺序:
<script type="text/babel">
ReactDOM.render(
<div id='app'>
Hello, chris!
<h1>
title
</h1>
</div>,
document.getElementById('container')
);
</script>
转换后的结果如下:
trans.png四、React.createElement执行顺序(ReactElement 生成顺序)
以上节第三点 div 与 h1 嵌套为例,babel 转换代码后,将依次从里到外,从上至下(若有兄弟节点)调用 React.createElement,创建 ReactElement对象,即可以理解为最终到根时,就生成了一棵 ReactElement Tree :
- 先调用 React.createElement 创建 h1 的 ReactElement对象;
- 然后再调用 React.createElement 创建 div 的 ReactElement对象;
五、React.createElement源码分析
源码稍微较长,这里将分段分析!
5.1 局部变量初始化
/**
* type = 'div'
* config = {id: 'app'}
* children = 'Hello, chris!'
* arguments[3] = {$$typeof: Symbol(react.element), type: 'h1',...}
*/
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;
......
}
5.2 config 解析
/**
* config = {id: 'app'}
*/
function createElement(type, config, children) {
......
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) {
if (
hasOwnProperty.call(config, propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)
) {
props[propName] = config[propName];
}
}
}
......
}
config对象中,没有 ref, key, __self, __source,只有 id: 'app',所以,props['id'] = 'app';
5.3 判断真实children个数
/**
* children = 'Hello, chris!'
* argument[3] = {$$typeof: Symbol(react.element), type: 'h1',...}
*/
function createElement(type, config, children) {
......
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
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];
}
if (__DEV__) {
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
}
......
}
arguments默认是3个参数:type、config、children(这里的是字符串 'Hello, chris!' );但是如果有嵌套HTML,则 arguments 就不止3个无数,会更多,所以,代码中,减去 arguments 前两个,判断剩下的个数,并最后赋值给 props(props['children'] = children 或 childArray );
5.4 如果 type 是对象,则判断是否有 defaultProps,有则赋值给 props
function createElement(type, config, children) {
......
// Resolve default props
if (type && type.defaultProps) {
const defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
......
}
5.5 返回 ReactElement 对象
function createElement(type, config, children) {
......
return ReactElement(
type,
key,
ref,
self,
source,
ReactCurrentOwner.current,
props,
);
}
5.6 ReactElement 方法(简单的封装成 REACT_ELEMENT_TYPE 对象)
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, no instanceof check
* will work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string | object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
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;
};
网友评论