React 源碼深度解讀(一):首次DOM元素渲染 - Part 1

歡迎關注個人公衆號睿Talk,獲取我最新的文章:
clipboard.pngjavascript

1、前言

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

2、React.createElement

在寫 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.createElementapp

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

  1. 將過濾後的有效屬性,從 config 拷貝到 props
  2. 將 children 以數組或對象的形式拷貝到 props.children
  3. 默認屬性賦值

最終的返回值是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。

3、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)

組件間的層級結構是這樣的:

clipboard.png

到此爲止,頂層對象已經構造完畢,下一步就是調用 batchedMountComponentIntoNode(來自 ReactMount 的 _renderNewRootComponent方法),進行頁面的渲染了。

4、總結

本文介紹了 React 頂層對象 ReactCompositeComponent 的構建過程。經過 JSX 表達的 DOM 結構最終會轉化爲一個純 JS 對象,用於下一步的渲染。

相關文章
相關標籤/搜索