最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
问答文章1 问答文章501 问答文章1001 问答文章1501 问答文章2001 问答文章2501 问答文章3001 问答文章3501 问答文章4001 问答文章4501 问答文章5001 问答文章5501 问答文章6001 问答文章6501 问答文章7001 问答文章7501 问答文章8001 问答文章8501 问答文章9001 问答文章9501
当前位置: 首页 - 科技 - 知识百科 - 正文

React首次渲染的解析一(纯DOM元素)

来源:懂视网 责编:小采 时间:2020-11-27 19:29:41
文档

React首次渲染的解析一(纯DOM元素)

React首次渲染的解析一(纯DOM元素):本篇文章给大家带来的内容是关于React首次渲染的解析(纯DOM元素),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。React 是一个十分庞大的库,由于要同时考虑 ReactDom 和 ReactNative ,还有服务器渲染等,导致其代码抽象化程度很高,嵌
推荐度:
导读React首次渲染的解析一(纯DOM元素):本篇文章给大家带来的内容是关于React首次渲染的解析(纯DOM元素),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。React 是一个十分庞大的库,由于要同时考虑 ReactDom 和 ReactNative ,还有服务器渲染等,导致其代码抽象化程度很高,嵌
本篇文章给大家带来的内容是关于React首次渲染的解析(纯DOM元素),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

React 是一个十分庞大的库,由于要同时考虑 ReactDom 和 ReactNative ,还有服务器渲染等,导致其代码抽象化程度很高,嵌套层级非常深,阅读其源码是一个非常艰辛的过程。在学习 React 源码的过程中,给我帮助最大的就是这个系列文章,于是决定基于这个系列文章谈一下自己的理解。本文会大量用到原文中的例子,想体会原汁原味的感觉,推荐阅读原文。

本系列文章将基于 React 15.4.2。

  • React.createElement

  • 在写 React 项目的时候,我们一般会直接用 JSX 的形式来写,而 JSX 经过 Babel 编译后最终会将 HTML 标签转换为React.createElement的函数形式。如果想进行更深入的了解,可以看我之前写的这篇文章:你不知道的Virtual DOM(一):Virtual Dom介绍。文章中的h函数,如果不在 Babel 中配置的话,默认就是React.createElement。

    下面,我们将从一个最简单的例子,来看React是如何渲染的

    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

    // 文件位置: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];
     }
     if (__DEV__) {
     if (Object.freeze) {
     Object.freeze(childArray);
     }
     }
     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件事:

    1. 将过滤后的有效的属性,从config拷贝到props

    2. 将children以数组的形式拷贝到props.children属性

    3. 默认属性赋值

    最终的返回值是ReactElement。我们再来看看它做了什么

    // 文件位置: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

  • 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;
    
     if (__DEV__) {
     this._warnedAboutRefsInRender = 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)

    组件间的层级结构是这样的:

    4100563483-5bc9a047e64c5_articlex.png

    当顶层组件构建完毕后,下一步就是调用 batchedMountComponentIntoNode(来自 ReactMount 的 _renderNewRootComponent方法),进行页面的渲染了。

    声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

    文档

    React首次渲染的解析一(纯DOM元素)

    React首次渲染的解析一(纯DOM元素):本篇文章给大家带来的内容是关于React首次渲染的解析(纯DOM元素),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。React 是一个十分庞大的库,由于要同时考虑 ReactDom 和 ReactNative ,还有服务器渲染等,导致其代码抽象化程度很高,嵌
    推荐度:
    标签: 讲解 首次 解析
    • 热门焦点

    最新推荐

    猜你喜欢

    热门推荐

    专题
    Top