成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

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

daydream / 1178人閱讀

摘要:調(diào)用棧是這樣的這里生成的我們將其命名為,它將作為參數(shù)傳入到。整個的調(diào)用棧是這樣的組件間的層級結(jié)構(gòu)是這樣的到此為止,頂層對象已經(jīng)構(gòu)造完畢,下一步就是調(diào)用來自的方法,進(jìn)行頁面的渲染了。通過表達(dá)的結(jié)構(gòu)最終會轉(zhuǎn)化為一個純對象,用于下一步的渲染。

歡迎關(guān)注我的公眾號睿Talk,獲取我最新的文章:

一、前言

React 是一個十分龐大的庫,由于要同時考慮 ReactDom 和 ReactNative ,還有服務(wù)器渲染等,導(dǎo)致其代碼抽象化程度很高,嵌套層級非常深。閱讀 React 源碼是一個非常艱辛的過程,在學(xué)習(xí)過程中給我?guī)椭畲蟮木褪沁@個系列文章。作者對代碼的調(diào)用關(guān)系梳理得非常清楚,而且還有配圖幫助理解,非常值得一讀。站在巨人的肩膀之上,我嘗試再加入自己的理解,希望對有志于學(xué)習(xí) React 源碼的讀者帶來一點啟發(fā)。

本系列文章基于 React 15.4.2 ,以下是本系列其它文章的傳送門:
React 源碼深度解讀(一):首次 DOM 元素渲染 - Part 1
React 源碼深度解讀(二):首次 DOM 元素渲染 - Part 2
React 源碼深度解讀(三):首次 DOM 元素渲染 - Part 3
React 源碼深度解讀(四):首次自定義組件渲染 - Part 1
React 源碼深度解讀(五):首次自定義組件渲染 - Part 2
React 源碼深度解讀(六):依賴注入
React 源碼深度解讀(七):事務(wù) - Part 1
React 源碼深度解讀(八):事務(wù) - Part 2
React 源碼深度解讀(九):單個元素更新
React 源碼深度解讀(十):Diff 算法詳解

二、React.createElement

在寫 React 項目的時候,我們一般會直接用 JSX 的形式來寫,而 JSX 經(jīng)過 Babel 編譯后會將 HTML 標(biāo)簽轉(zhuǎn)換為React.createElement的函數(shù)形式。如果想進(jìn)行更深入的了解這一過程,可以看我之前寫的這篇文章:你不知道的Virtual DOM(一):Virtual Dom介紹。文章中的h函數(shù),如果在 Babel 中沒有特別指定的話,默認(rèn)就是React.createElement。

下面,我們將從一個最簡單的例子,來看React是如何渲染的:

ReactDOM.render(
    

hello world

, document.getElementById("root") );

經(jīng)過 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;

最終的實現(xiàn)需要查看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以數(shù)組的形式拷貝到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. 默認(rèn)屬性賦值
    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
    );
};

本質(zhì)上只做了3件事:

將過濾后的有效屬性,從 config 拷貝到 props

將 children 以數(shù)組或?qū)ο蟮男问娇截惖?props.children

默認(rèn)屬性賦值

最終的返回值是ReactElement函數(shù)的調(diào)用結(jié)果。我們再來看看它做了什么:

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

最終只是返回一個簡單對象。調(diào)用棧是這樣的:

React.createElement
|=ReactElement.createElement(type, config, children)
    |-ReactElement(type,..., props)

這里生成的 ReactElement 我們將其命名為ReactElement[1],它將作為參數(shù)傳入到 ReactDom.render。

三、ReactDom.render

ReactDom.render 最終會調(diào)用 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;
},

這里又會調(diào)用到另一個文件 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,
    }
);

這里又會調(diào)用到另一個文件 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。

整個的調(diào)用棧是這樣的:

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)

組件間的層級結(jié)構(gòu)是這樣的:

到此為止,頂層對象已經(jīng)構(gòu)造完畢,下一步就是調(diào)用 batchedMountComponentIntoNode(來自 ReactMount 的 _renderNewRootComponent方法),進(jìn)行頁面的渲染了。

四、總結(jié)

本文介紹了 React 頂層對象 ReactCompositeComponent 的構(gòu)建過程。通過 JSX 表達(dá)的 DOM 結(jié)構(gòu)最終會轉(zhuǎn)化為一個純 JS 對象,用于下一步的渲染。

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/98512.html

相關(guān)文章

  • React 源碼深度解讀(三):首次 DOM 元素渲染 - Part 3

    摘要:在學(xué)習(xí)源碼的過程中,給我?guī)椭畲蟮木褪沁@個系列文章,于是決定基于這個系列文章談一下自己的理解。到此為止,首次渲染就完成啦總結(jié)從啟動到元素渲染到頁面,并不像看起來這么簡單,中間經(jīng)歷了復(fù)雜的層級調(diào)用。 前言 React 是一個十分龐大的庫,由于要同時考慮 ReactDom 和 ReactNative ,還有服務(wù)器渲染等,導(dǎo)致其代碼抽象化程度很高,嵌套層級非常深,閱讀其源碼是一個非常艱辛的過...

    U2FsdGVkX1x 評論0 收藏0
  • React 源碼深度解讀(四):首次自定義組件渲染 - Part 1

    摘要:本篇開始介紹自定義組件是如何渲染的。組件將自定義組件命名為,結(jié)構(gòu)如下經(jīng)過編譯后,生成如下代碼構(gòu)建頂層包裝組件跟普通元素渲染一樣,第一步先會執(zhí)行創(chuàng)建為的。調(diào)用順序已在代碼中注釋。先看圖,這部分內(nèi)容將在下回分解 前言 React 是一個十分龐大的庫,由于要同時考慮 ReactDom 和 ReactNative ,還有服務(wù)器渲染等,導(dǎo)致其代碼抽象化程度很高,嵌套層級非常深,閱讀其源碼是一個非...

    Warren 評論0 收藏0
  • React 源碼深度解讀(二):首次 DOM 元素渲染 - Part 2

    摘要:本文將要講解的調(diào)用棧是下面這個樣子的平臺無關(guān)相關(guān)如果看源碼,我們會留意到很多相關(guān)的代碼,我們暫時先將其忽略,會在后續(xù)的文章中進(jìn)行講解?,F(xiàn)在我們來看一下各實例間的關(guān)系目前為止的調(diào)用棧平臺無關(guān)相關(guān)下一篇講解三總結(jié)本文講解了轉(zhuǎn)化為的過程。 歡迎關(guān)注我的公眾號睿Talk,獲取我最新的文章:showImg(https://segmentfault.com/img/bVbmYjo); 一、前言 R...

    wean 評論0 收藏0
  • React 源碼深度解讀(五):首次自定義組件渲染 - Part 2

    摘要:的和真正有效的都各只有一行代碼的調(diào)用棧如下這中間的函數(shù)調(diào)用邏輯很清晰,最終會走到這里這里的邏輯很簡單,如果不是數(shù)組,則調(diào)用回調(diào)函數(shù)如果是數(shù)組,則繼續(xù)調(diào)用自身,相當(dāng)于深度優(yōu)先遍歷。這里的回調(diào)函數(shù)就是中的這里直接調(diào)用,創(chuàng)建。 前言 React 是一個十分龐大的庫,由于要同時考慮 ReactDom 和 ReactNative ,還有服務(wù)器渲染等,導(dǎo)致其代碼抽象化程度很高,嵌套層級非常深,閱讀...

    william 評論0 收藏0
  • React 源碼深度解讀(八):事務(wù) - Part 2

    摘要:前言是一個十分龐大的庫,由于要同時考慮和,還有服務(wù)器渲染等,導(dǎo)致其代碼抽象化程度很高,嵌套層級非常深,閱讀其源碼是一個非常艱辛的過程。在學(xué)習(xí)源碼的過程中,給我?guī)椭畲蟮木褪沁@個系列文章,于是決定基于這個系列文章談一下自己的理解。 前言 React 是一個十分龐大的庫,由于要同時考慮 ReactDom 和 ReactNative ,還有服務(wù)器渲染等,導(dǎo)致其代碼抽象化程度很高,嵌套層級非常...

    airborne007 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<