登录  /  注册
首页 > web前端 > js教程 > 正文

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

不言
发布: 2018-10-20 14:38:00
转载
2458人浏览过

本篇文章给大家带来的内容是关于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>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) &amp;&amp;
                !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 &gt; 1) {
        var childArray = Array(childrenLength);
        for (var i = 0; i <p>本质上只做了3件事:</p><ol class=" list-paddingleft-2">
<li><p>将过滤后的有效的属性,从config拷贝到props</p></li>
<li><p>将children以数组的形式拷贝到props.children属性</p></li>
<li><p>默认属性赋值</p></li>
</ol><p>最终的返回值是<code>ReactElement</code>。我们再来看看它做了什么</p><pre class="brush:php;toolbar:false">// 文件位置: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:------------------&gt; ReactElement[2]
        container,          // scr:------------------&gt; document.getElementById('root')
        shouldReuseMarkup,  // scr: null from ReactDom.render()
        nextContext,        // scr: emptyObject from ReactDom.render()
    )
    |-instantiateReactComponent(
          node,             // scr:------------------&gt; ReactElement[2]
          shouldHaveDebugID /* false */
        )
        |-ReactCompositeComponentWrapper(
            element         // scr:------------------&gt; ReactElement[2]
        );
        |=ReactCompositeComponent.construct(element)
登录后复制

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

4100563483-5bc9a047e64c5_articlex.png

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


以上就是React首次渲染的解析一(纯DOM元素)的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:segmentfault思否网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号