欢迎关注个人公众号睿Talk
,获取我最新的文章:javascript
React 是一个十分庞大的库,因为要同时考虑 ReactDom 和 ReactNative ,还有服务器渲染等,致使其代码抽象化程度很高,嵌套层级很是深。阅读 React 源码是一个很是艰辛的过程,在学习过程当中给我帮助最大的就是这个系列文章。做者对代码的调用关系梳理得很是清楚,并且还有配图帮助理解,很是值得一读。站在巨人的肩膀之上,我尝试再加入本身的理解,但愿对有志于学习 React 源码的读者带来一点启发。java
本系列文章基于 React 15.4.2 ,如下是本系列其它文章的传送门:
React 源码深度解读(一):首次 DOM 元素渲染 - Part 1
React 源码深度解读(二):首次 DOM 元素渲染 - Part 2
React 源码深度解读(三):首次 DOM 元素渲染 - Part 3
React 源码深度解读(四):首次自定义组件渲染 - Part 1
React 源码深度解读(五):首次自定义组件渲染 - Part 2
React 源码深度解读(六):依赖注入
React 源码深度解读(七):事务 - Part 1
React 源码深度解读(八):事务 - Part 2
React 源码深度解读(九):单个元素更新
React 源码深度解读(十):Diff 算法详解node
在写 React 项目的时候,咱们通常会直接用 JSX 的形式来写,而 JSX 通过 Babel 编译后会将 HTML 标签转换为React.createElement
的函数形式。若是想进行更深刻的了解这一过程,能够看我以前写的这篇文章:你不知道的Virtual DOM(一):Virtual Dom介绍。文章中的h
函数,若是在 Babel 中没有特别指定的话,默认就是React.createElement
。算法
下面,咱们将从一个最简单的例子,来看React是如何渲染的:segmentfault
ReactDOM.render( <h1 style={{"color":"blue"}}>hello world</h1>, document.getElementById('root') );
通过 JSX 编译后,会是下面这个样子:数组
ReactDOM.render( React.createElement( 'h1', { style: { "color": "blue" } }, 'hello world' ), document.getElementById('root') );
先来看下React.createElement
的源码。服务器
// 文件位置:src/isomorphic/React.js var ReactElement = require('ReactElement'); ... var createElement = ReactElement.createElement; ... var React = { ... createElement: createElement, ... } module.exports = React;
最终的实现须要查看ReactElement.createElement
:app
// 文件位置:src/isomorphic/classic/element/ReactElement.js ReactElement.createElement = function (type, config, children) { ... // 1. 将过滤后的有效的属性,从config拷贝到props if (config != null) { ... for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // 2. 将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]; } props.children = childArray; } // 3. 默认属性赋值 if (type && type.defaultProps) { var 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 ); };
本质上只作了3件事:dom
最终的返回值是ReactElement
函数的调用结果。咱们再来看看它作了什么:ide
// 文件位置:src/isomorphic/classic/element/ReactElement.js var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow 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; };
最终只是返回一个简单对象。调用栈是这样的:
React.createElement |=ReactElement.createElement(type, config, children) |-ReactElement(type,..., props)
这里生成的 ReactElement 咱们将其命名为ReactElement[1]
,它将做为参数传入到 ReactDom.render。
ReactDom.render 最终会调用 ReactMount 的 _renderSubtreeIntoContainer:
// 文件位置:src/renderers/dom/client/ReactMount.js _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { ... var nextWrappedElement = React.createElement( TopLevelWrapper, { child: nextElement } ); ... var component = ReactMount._renderNewRootComponent( nextWrappedElement, container, shouldReuseMarkup, nextContext )._renderedComponent.getPublicInstance(); ... return component; }, ... var TopLevelWrapper = function () { this.rootID = topLevelRootCounter++; }; TopLevelWrapper.prototype.isReactComponent = {}; TopLevelWrapper.prototype.render = function () { return this.props.child; }; TopLevelWrapper.isReactTopLevelWrapper = true; ... _renderNewRootComponent: function ( nextElement, container, shouldReuseMarkup, context ) { ... var componentInstance = instantiateReactComponent(nextElement, false); ... return componentInstance; },
这里又会调用到另外一个文件 instantiateReactComponent:
// 文件位置:src/renders/shared/stack/reconciler/instantiateReactComponent.js function instantiateReactComponent(node, shouldHaveDebugID) { var instance; ... instance = new ReactCompositeComponentWrapper(element); ... return instance; } // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; Object.assign( ReactCompositeComponentWrapper.prototype, ReactCompositeComponent, { _instantiateReactComponent: instantiateReactComponent, } );
这里又会调用到另外一个文件 ReactCompositeComponent:
// 文件位置:src/renders/shared/stack/reconciler/ReactCompositeComponent.js var ReactCompositeComponent = { construct: function (element) { this._currentElement = element; this._rootNodeID = 0; this._compositeType = null; this._instance = null; this._hostParent = null; this._hostContainerInfo = null; // See ReactUpdateQueue this._updateBatchNumber = null; this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; ... } ... }
咱们用ReactCompositeComponent[T]
来表示这里生成的顶层 component。
整个的调用栈是这样的:
ReactDOM.render |=ReactMount.render(nextElement, container, callback) |=ReactMount._renderSubtreeIntoContainer() |-ReactMount._renderNewRootComponent( nextWrappedElement, // scr:------------------> ReactElement[2] container, // scr:------------------> document.getElementById('root') shouldReuseMarkup, // scr: null from ReactDom.render() nextContext, // scr: emptyObject from ReactDom.render() ) |-instantiateReactComponent( node, // scr:------------------> ReactElement[2] shouldHaveDebugID /* false */ ) |-ReactCompositeComponentWrapper( element // scr:------------------> ReactElement[2] ); |=ReactCompositeComponent.construct(element)
组件间的层级结构是这样的:
到此为止,顶层对象已经构造完毕,下一步就是调用 batchedMountComponentIntoNode(来自 ReactMount 的 _renderNewRootComponent方法),进行页面的渲染了。
本文介绍了 React 顶层对象 ReactCompositeComponent 的构建过程。经过 JSX 表达的 DOM 结构最终会转化为一个纯 JS 对象,用于下一步的渲染。