React@15.6.2源碼解析---從 ReactDOM.render 到頁(yè)面渲染(2)instantiateReactComponent

instantiateReactComponent 方法是React中的一個(gè)很重要的方法,主要作用是根據(jù)給定的node(ReactElement類型)對(duì)象,實(shí)例化出一個(gè)將被掛載的實(shí)例。實(shí)例化出的實(shí)例大體有三種密末,ReactEmptyComponent、ReactCompositeComponent、ReactHostComponent楞捂,其中ReactCompositeComponent是重點(diǎn),內(nèi)部包裝了很多方法趋厉,而ReactHostComponent主要用來(lái)實(shí)例化文本組件實(shí)例寨闹。

概述
Given a ReactNode, create an instance that will actually be mounted.
給一個(gè)ReactNode 指的是 ReactElement 對(duì)象,根據(jù)該對(duì)象創(chuàng)建一個(gè)實(shí)際要掛載的實(shí)例

大致流程
判斷 node 的類型以及 node.type 的類型君账,根據(jù)不同的類型創(chuàng)建不同的實(shí)例

node 為 null | false

if (node === null || node === false) {
    instance = ReactEmptyComponent.create(instantiateReactComponent);
  } else if (typeof node === 'object') {
    var element = node;
    var type = element.type; // function
    if (typeof type !== 'function' && typeof type !== 'string') {
      var info = '';
      if (process.env.NODE_ENV !== 'production') {
        /**/
      }
      info += getDeclarationErrorAddendum(element._owner); // ''
      !false ? /**/
    }

    // Special case string values
    if (typeof element.type === 'string') {
      instance = ReactHostComponent.createInternalComponent(element);
    } else if (isInternalComponentType(element.type)) {
      if (!instance.getHostNode) {
        instance.getHostNode = instance.getNativeNode;
      }
    } else {
      instance = new ReactCompositeComponentWrapper(element);
    }
  } else if (typeof node === 'string' || typeof node === 'number') {
    instance = ReactHostComponent.createInstanceForText(node);
  } else {
    !false ? /**/
  }

node 的類型是null或者為false繁堡,創(chuàng)建一個(gè)ReactEmptyComponent實(shí)例。

ReactEmptyComponent

// ReactEmptyComponent.js
var emptyComponentFactory;

var ReactEmptyComponentInjection = {
  injectEmptyComponentFactory: function (factory) {
    emptyComponentFactory = factory;
  }
};

var ReactEmptyComponent = {
  create: function (instantiate) {
    return emptyComponentFactory(instantiate);
  }
};

ReactEmptyComponent.injection = ReactEmptyComponentInjection;

module.exports = ReactEmptyComponent;

這邊可以看出ReactEmptyComponent.create方法就是調(diào)用emptyComponentFactory()方法乡数,而emptyComponentFactory是外部閉包的一個(gè)對(duì)象椭蹄,是在全局依賴注入是調(diào)用ReactEmptyComponent.injection時(shí)進(jìn)行注入的。注入的地方在ReactDefaultInjection.js文件净赴,這也是上一篇博客的開頭所闡述的全局依賴注入塑娇,作用就在于給一些函數(shù)外部閉包的變量對(duì)象某個(gè)屬性進(jìn)行賦值,這樣做方便管理劫侧,神乎其技的封裝埋酬。我覺(jué)得這種優(yōu)秀的封裝也是我們?cè)搶W(xué)習(xí)的一部分。有助于我們寫出更加完善的代碼烧栋。

ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) {
    return new ReactDOMEmptyComponent(instantiate);
  });

那么這邊給emptyComponentFactory賦值的是一個(gè)函數(shù)写妥,這個(gè)函數(shù)返回一個(gè)new ReactDOMEmptyComponent(instantiate);ReactDOMEmptyComponent實(shí)例。

ReactDOMEmptyComponent實(shí)例

var ReactDOMEmptyComponent = function (instantiate) {
  // ReactCompositeComponent uses this:
  this._currentElement = null;
  // ReactDOMComponentTree uses these:
  this._hostNode = null;
  this._hostParent = null;
  this._hostContainerInfo = null;
  this._domID = 0;
};
_assign(ReactDOMEmptyComponent.prototype, {
  mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
    /**/
    }
  },
  receiveComponent: function () {},
  getHostNode: function () {
    return ReactDOMComponentTree.getNodeFromInstance(this);
  },
  unmountComponent: function () {
    ReactDOMComponentTree.uncacheNode(this);
  }
});

這邊我們大致了解一下有那些屬性等用到時(shí)在做闡述审姓。那么由此可以看出珍特,ReactEmptyComponent創(chuàng)建的實(shí)例實(shí)質(zhì)上就是ReactDOMEmptyComponent

node 為 object##

當(dāng) node 的類型為一個(gè)object時(shí)魔吐,這邊大多數(shù)情況指的是我們的node是一個(gè)ReactElement扎筒。接下來(lái)會(huì)對(duì)node.type做判斷莱找。

node.type !== function || node.type !== string

當(dāng) type 既不是 function 也不是一個(gè) string 那么會(huì)報(bào)一個(gè)警告,講道理要么是一個(gè)構(gòu)造函數(shù)例如我們的App嗜桌,那么是一個(gè)字符串例如一個(gè)div標(biāo)簽奥溺,下面給一個(gè)例子

node一層層剝開,看他的child骨宠,劇透一下浮定,后面一步步的忘深處創(chuàng)建實(shí)例,那么肯定會(huì)遇到一個(gè)type: 'div'的ReactElement层亿,這個(gè)時(shí)候 type 就是string了

node.type === string

那么當(dāng)node.type是一個(gè)字符串的時(shí)候桦卒,會(huì)創(chuàng)建一個(gè)ReactHostComponet實(shí)例,這邊和文本節(jié)點(diǎn)有所區(qū)別匿又,這邊調(diào)用的是ReactHostComponet.createInternalComponent方法方灾,文本節(jié)點(diǎn)的話會(huì)調(diào)用ReactHostComponet.createInstanceForText下方會(huì)遇到。

// ReactHostComponent.js
function createInternalComponent(element) {
  !genericComponentClass /**/
  return new genericComponentClass(element);
}

這個(gè)函數(shù)首先會(huì)判斷genericComponentClass是否存在碌更,而這個(gè)變量是函數(shù)外部閉包的一個(gè)變量迎吵,和之前一樣是在全局依賴注入的時(shí)候完成了賦值。

var ReactHostComponentInjection = {
  // This accepts a class that receives the tag string. This is a catch all
  // that can render any kind of tag.
  injectGenericComponentClass: function (componentClass) {
    genericComponentClass = componentClass;
  },
  // This accepts a text component class that takes the text string to be
  // rendered as props.
  injectTextComponentClass: function (componentClass) {
    textComponentClass = componentClass;
  }
};

那么回到ReactDefaultInjection繼續(xù)查找這邊注入的是什么

ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent);

那么此時(shí)genericComponentClass就是這邊傳入的ReactDOMComponent针贬,那么就是返回一個(gè)ReactDOMComponent實(shí)例

isInternalComponentType(element.type)

檢測(cè) node.type 是不是內(nèi)部組件類型

function isInternalComponentType(type) {
  return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function';
}

如果是內(nèi)部的類型的化击费,那么就直接實(shí)例化傳入的node,具體例子我還沒(méi)有遇到過(guò)桦他,就不做過(guò)多理解了蔫巩,有例子的同學(xué)歡迎指教。

node.type 不是上述類型

其實(shí)這邊的意思就是 node.type 是一個(gè)function快压,因?yàn)?node.type 只能是 function 或者 string圆仔。只不過(guò)逃過(guò)了上述isInternalComponentType函數(shù)的檢測(cè)。
那么這邊是創(chuàng)建的一個(gè)ReactCompositeComponentWrapper實(shí)例蔫劣,這個(gè)構(gòu)造函數(shù)是React的一大重點(diǎn)坪郭,根據(jù)我的四級(jí)英語(yǔ)翻譯為 ' React復(fù)合類型 ' 他的本質(zhì)是ReactCompositeComponet內(nèi)部實(shí)現(xiàn)了React的組件生命周期,掛載卸載等操作脉幢。具體的后面會(huì)有很大一部分講解他歪沃。這也是代碼量可以說(shuō)最大的幾個(gè)文件之一了。

// 這邊是定義了一下這個(gè)構(gòu)造函數(shù)嫌松,在該文件的最下面沪曙,對(duì)該構(gòu)造函數(shù)的原型鏈添加了一系列的方法
var ReactCompositeComponentWrapper = function (element) {
  this.construct(element);
  // console.log(this);
};

_assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent, {
  _instantiateReactComponent: instantiateReactComponent
});

這邊可以看出ReactCompositeComponentWrapper的主要操作都在ReactCompositeComponent文件里,而這邊覆蓋了一個(gè)_instantiateReactComponent屬性萎羔,值為當(dāng)前講解的這個(gè)創(chuàng)建實(shí)例的函數(shù)instantiateReactComponent

node 為 string | number

當(dāng) node 為 string 或者 number 時(shí)液走,表明這是一個(gè)文本組件,對(duì)調(diào)用ReactHostComponent.createInstanceForText,那么加上當(dāng) node.type 為 string 時(shí)的講解缘眶,可以看出ReactHostComponent組件描述的都是React中的文本組件嘱根。而ReactHostComponent.createInstanceForText方法引用的是外部閉包的textComponentClass,一樣也是在全局依賴注入的時(shí)候賦值的巷懈。

// ReactHostComponent.js
/**
 * @param {ReactText} text
 * @return {ReactComponent}
 */
function createInstanceForText(text) {
  return new textComponentClass(text);
}

// ReactDefaultInjection.js
ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent);

那么本質(zhì)就是創(chuàng)建一個(gè) ReactDOMTextComponent 實(shí)例该抒。

node 不是上述類型

這邊不是上述類型,那么就報(bào)錯(cuò)了砸喻。

新增 _mountIndex _mountIage

在得到實(shí)例之后柔逼,會(huì)給instance添加兩個(gè)額外的屬性蒋譬。根據(jù)官方給的英文注釋割岛,大致可以猜出這兩個(gè)字段是用于 DOM 和 Diff 算法上的。React的Diff算法我也會(huì)寫博客講解犯助,只不過(guò)得等這個(gè)渲染的一系列寫完癣漆。React萬(wàn)歲!<谅颉惠爽!

 // These two fields are used by the DOM and ART diffing algorithms
  // respectively. Instead of using expandos on components, we should be
  // storing the state needed by the diffing algorithms elsewhere.
  // 這兩個(gè)字段是 DOM 和 ART diff算法所需要的字段。我們應(yīng)該在其他地方存儲(chǔ)diff算法所需要的state瞬哼,
  // 而不是在組件上擴(kuò)展他
  // 這兩個(gè)字段分別用于DOM和ART diffing算法婚肆。我們不應(yīng)該在組件上使用expandos,而是應(yīng)該存儲(chǔ)其他不同算法所需的狀態(tài)坐慰。
  instance._mountIndex = 0;
  instance._mountIage = null;

總結(jié)

instantiateReactComponent 函數(shù)總體來(lái)說(shuō)還是很簡(jiǎn)單的较性,只是根據(jù) node 的類型 和 node.type 的類型創(chuàng)建一個(gè)實(shí)例,這邊的代碼還是可以理解的结胀,不了解實(shí)例內(nèi)部的那些方法的話難度還是可以接受的赞咙,難的地方還在后面,那么對(duì)該函數(shù)做一個(gè)流程圖如下

本片留坑

各個(gè)實(shí)例的內(nèi)部屬性糟港、方法

坑總會(huì)填的攀操,不急不急

下一篇講解 ReactUpdates.js 這也是一個(gè)重點(diǎn),博客是按照整個(gè)渲染的流程秸抚,部分重點(diǎn)文件會(huì)單獨(dú)拉出來(lái)一篇進(jìn)行理解速和。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市剥汤,隨后出現(xiàn)的幾起案子健芭,更是在濱河造成了極大的恐慌,老刑警劉巖秀姐,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件慈迈,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)痒留,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門谴麦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人伸头,你說(shuō)我怎么就攤上這事匾效。” “怎么了恤磷?”我有些...
    開封第一講書人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵面哼,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我扫步,道長(zhǎng)魔策,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任河胎,我火速辦了婚禮闯袒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘游岳。我一直安慰自己政敢,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開白布胚迫。 她就那樣靜靜地躺著喷户,像睡著了一般。 火紅的嫁衣襯著肌膚如雪访锻。 梳的紋絲不亂的頭發(fā)上褪尝,一...
    開封第一講書人閱讀 49,929評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音朗若,去河邊找鬼恼五。 笑死,一個(gè)胖子當(dāng)著我的面吹牛哭懈,可吹牛的內(nèi)容都是我干的灾馒。 我是一名探鬼主播,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼遣总,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼睬罗!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起旭斥,我...
    開封第一講書人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤容达,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后垂券,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體花盐,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了算芯。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片柒昏。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖熙揍,靈堂內(nèi)的尸體忽然破棺而出职祷,到底是詐尸還是另有隱情,我是刑警寧澤届囚,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布有梆,位于F島的核電站,受9級(jí)特大地震影響意系,放射性物質(zhì)發(fā)生泄漏泥耀。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一昔字、第九天 我趴在偏房一處隱蔽的房頂上張望爆袍。 院中可真熱鬧首繁,春花似錦作郭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至胁塞,卻和暖如春咏尝,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背啸罢。 一陣腳步聲響...
    開封第一講書人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工编检, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人扰才。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓允懂,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親衩匣。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蕾总,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容