React學(xué)習(xí)---渲染機(jī)制

? ?? ?在介紹React渲染機(jī)制之間先來(lái)說(shuō)一說(shuō)下面幾個(gè)概念,對(duì)于新入手React的學(xué)員來(lái)說(shuō),經(jīng)常會(huì)被搞蒙圈。
? ?? ?React與ReactDOM區(qū)別
? ?? ?在v0.14前,ReactDOM是React的函數(shù),之所以在v0.14之后分成兩個(gè)包是package是因?yàn)?/p>

? ?? ?As we look at packages like react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.
? ?? ?To make this more clear and to make it easier to build more environments that React can render to, we’re splitting the main react package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native. We don’t expect all the code in an app to be shared, but we want to be able to share the components that do behave the same across platforms.

? ?? ?可見,React分為react-dom和react的原因是React-Native的出現(xiàn),它可以實(shí)現(xiàn)跨平臺(tái)實(shí)現(xiàn)相同的組件。
? ?? ?react包包含了React.createElement、 .createClass、 .Component、 .PropTypes、.Children以及其他的描述元素和組件的類。
? ?? ?react-dom包包含了ReactDOM.render、.unmountComponentAtNode和.findDOMNode等。下面看一個(gè)創(chuàng)建組件的實(shí)例:

var React = require('react');
var ReactDOM = require('react-dom');
var MyComponent = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
ReactDOM.render(<MyComponent />, node);

? ?? ?ReactDOM.render是React的最基本方法用于將模板轉(zhuǎn)為HTML語(yǔ)言,并插入指定的DOM節(jié)點(diǎn)。它可以將一個(gè)React元素呈現(xiàn)在指定的DOM container中,并返回對(duì)組件的引用對(duì)象。

? ?? ?Component、Element和Component

? ?? ? Component
? ?? ?Component組件就是JavaScript函數(shù),可以接受任意參數(shù)。可以使用createClass和Component創(chuàng)建組件。createClass如其名就是創(chuàng)建React組件對(duì)應(yīng)的類,描述你將要?jiǎng)?chuàng)建組件的各種行為,其中只有當(dāng)組件被渲染時(shí)需要輸出的內(nèi)容的render接口是必須實(shí)現(xiàn)的,其他都是可選:

var SayHello = React.createClass({
      render: function() {
      return <div>Hello {this.props.name}</div>;
    }
});

從 React 0.13 開始,可以使用 ES6 Class代替 React.createClass了

class SayHello extends React.Component {
render() {
return <div>Hello {this.props.name}</a> </div>;
}
}

注意:(1)為了區(qū)分Component和DOM 元素,所有Component名字要首字母大寫。
? ?? ?(2)所有的React組件都不能修改它的prop屬性的值
? ?? ? Element
? ?? ?Element是class的一個(gè)實(shí)例,它描述DOM節(jié)點(diǎn)或component實(shí)例的字面級(jí)對(duì)象。它包含一些信息,包括組件類型type和屬性props。就像一個(gè)描述DOM節(jié)點(diǎn)的元素(虛擬節(jié)點(diǎn))。可以使用createElement,創(chuàng)建React組件實(shí)例

ReactElement.createElement= function(type, config, children) {
...
}

在上一篇文章中我們已經(jīng)講到,當(dāng)我們用JSX來(lái)描述< SayHello />時(shí) ,編譯后就是React.createElement()。
? ?? ?Factory
? ?? ?React.createFactory和ReactElement.createElement一樣,但是
Factory返回的是給定元素類型或組件類的實(shí)例。React.createFactory的定義基本就是如下形式,Element 的類型被提前綁定了

ReactElement.createFactory = function (type) {
var factory = ReactElement.createElement.bind(null, type);
    factory.type = type;
    return factory;
};

官方鼓勵(lì)使用JSX或者React.creatElement。下面進(jìn)入今天的主題:React的渲染機(jī)制
? ?? ?React渲染機(jī)制
? ?? ?假設(shè)要實(shí)現(xiàn)的渲染代碼如下:

  class Form extends React.Component {
    constructor() {
    super();
  }
  render() {
    return (
        <form>
          <input type="text"/>
        </form>
    );
  }
}

ReactDOM.render( (
  <div className="test">
    <p>請(qǐng)輸入你的信息</p>
    <Form/>
  </div>
), document.getElementById('example'))

? ?? ?從ReactDOM入口開始,找到ReactDOM.js文件

var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactDefaultInjection = require('./ReactDefaultInjection');
var ReactMount = require('./ReactMount');
var ReactReconciler = require('./ReactReconciler');
var ReactUpdates = require('./ReactUpdates');
var ReactVersion = require('./ReactVersion');

var findDOMNode = require('./findDOMNode');
var getHostComponentFromComposite = require('./getHostComponentFromComposite');
var renderSubtreeIntoContainer = require('./renderSubtreeIntoContainer');
var warning = require('fbjs/lib/warning');
ReactDefaultInjection.inject(); 
var ReactDOM = {
  findDOMNode: findDOMNode,
  render: ReactMount.render,
  unmountComponentAtNode: ReactMount.unmountComponentAtNode,
  version: ReactVersion,

  /* eslint-disable camelcase */
  unstable_batchedUpdates: ReactUpdates.batchedUpdates,
  unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
  /* eslint-enable camelcase */
};

? ?? ?ReactDOM.render()方法來(lái)自ReactMount文件的render方法:

render: function (nextElement, container, callback) {
    return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
  },

? ?? ? Render方法返回的是當(dāng)前文件下的_renderSubtreeIntoContainer方法,顧名思義,它的作用是將子樹nextElement注入到指定的container中,并調(diào)用其回調(diào)方法_renderSubtreeIntoContainer方法主要完成以下一個(gè)功能:

  1. 調(diào)用React.createElement生成待插入節(jié)點(diǎn)的虛擬DOM的實(shí)例對(duì)象(上篇文章中已經(jīng)講到,這里就不再重復(fù)敘述)
  2. 與之前的component比較,如果是初次渲染直接將虛擬DOM轉(zhuǎn)換為真實(shí)DOM
  3. 將真實(shí)的組件寫到對(duì)應(yīng)的container節(jié)點(diǎn)中
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
/*
*將callback放入到React的更新隊(duì)列中,判斷nextElement有效性以及當(dāng)前是發(fā)開環(huán)境還是生產(chǎn)環(huán)境。(代碼省略)
*/
…

var nextWrappedElement = React.createElement(TopLevelWrapper, {child: nextElement});
// 返回一個(gè)ReactElement實(shí)例對(duì)象,也就是虛擬DOM的實(shí)例對(duì)象,下面就要把它渲染出來(lái)
var nextContext;
/*(1)判斷是否有parentComponent,如果有則將其寫到parentComponent*/
if (parentComponent) {
var parentInst = ReactInstanceMap.get(parentComponent);
nextContext = parentInst._processChildContext(parentInst._context);
} else {
nextContext = emptyObject;
}

var prevComponent =getTopLevelWrapperInContainer(container);
 /*
*(2)判斷是否有prevComponent,如果有則取其child,利用Diff算法判斷是否需要更新,如果需要?jiǎng)t調(diào)用_updateRootComponen 方法,并return結(jié)果。對(duì)于初次渲染不需要該過(guò)程。 
*/

if (prevComponent) {
var prevWrappedElement = prevComponent._currentElement;
var prevElement = prevWrappedElement.props.child;
 // shouldUpdateReactComponent方法判斷是否需要更新,對(duì)同一DOM進(jìn)行比較,type相同,key(如果有)相同的組件做DOM diff 

if (shouldUpdateReactComponent(prevElement, nextElement)) {
var publicInst = prevComponent._renderedComponent.getPublicInstance();
var updatedCallback = callback && function () {
callback.call(publicInst);
};
ReactMount._updateRootComponent(prevComponent, nextWrappedElement, nextContext, container, updatedCallback);
return publicInst;
} else {
ReactMount.unmountComponentAtNode(container);
}
}
/*
*(3)對(duì)于prevElement為null直接跳到此步
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement);
var containerHasNonRootReactChild = hasNonRootReactChild(container);
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
/*
*3核心部分,調(diào)用_renderNewRootComponent,_renderedComponent,getPublicInstance三個(gè)方法,
*/
var component =ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
}

下面來(lái)看一看RenderNewRootComponent方法的源碼

(1)_renderNewRootComponent:

_renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) {
… …
 /*
*第一部分是調(diào)用instantiateReactComponen方法返回虛擬DOM對(duì)應(yīng)的DOM,并將其返回結(jié)果作為_renderNewRootComponent的最終返回結(jié)果 
*/
var componentInstance = <a name="OLE_LINK14"></a> <a name="OLE_LINK13">instantiateReactComponent</a> (nextElement, false);
return componentInstance;
 /*
*第二部分是處理batchedMountComponentIntoNode方法,并將上面的結(jié)果componentInstance 結(jié)果插入到DOM中
*/*

ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context);
var wrapperID = componentInstance._instance.rootID;
instancesByReactRootID[wrapperID] = componentInstance;
return componentInstance;
}

解析第一部分:將虛擬DOM生成DOM
? ?? ? 再來(lái)看一看instantiateReactComponent方法,它是從instantiateReactComponent文件require進(jìn)來(lái)的,輸入?yún)?shù)是虛擬DOM節(jié)點(diǎn),主要實(shí)現(xiàn)的功能是將虛擬DOM生成DOM。根element的類型不同,分別實(shí)例化ReactDOMTextComponent, ReactDOMComponent, ReactCompositeComponent類。
下面來(lái)看一看instantiateReactComponent.js源碼的偽代碼

function instantiateReactComponent(node, shouldHaveDebugID) {
var instance;
/*
*判斷node類型,不同的類型調(diào)用不同的渲染方法
*/
/*節(jié)點(diǎn)為空*/
instance = ReactEmptyComponent.create(instantiateReactComponent); 
/*如果節(jié)點(diǎn)是宿主內(nèi)置節(jié)點(diǎn),譬如瀏覽器的 的節(jié)點(diǎn)*/
instance = ReactHostComponent.createInternalComponent(element);

instance = new ReactCompositeComponentWrapper(element);
/*如果節(jié)點(diǎn)是字符串或數(shù)字*/
instance = ReactHostComponent.createInstanceForText(node);
return instance;
}

解析第二部分:將新的component分批插入到DOM中
? ?? ? batchedUpdates是ReactUpdates的一個(gè)方法,使用batchingStrategy更新DOM

function batchedUpdates(callback, a, b, c, d, e) {
ensureInjected();
return batchingStrategy .batchedUpdates(callback, a, b, c, d, e);
}

? ?? ? batchedUpdates 方法的回調(diào)函數(shù)是batchedMountComponentIntoNode方法

function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */
!shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement);
transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}

batchedMountComponentIntoNode 方法通過(guò)
transaction.perform調(diào)用mountComponentIntoNode方法。

/*
* Mounts this component and inserts it into the DOM.
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) {
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var wrappedElement = wrapperInstance._currentElement.props.child;
var type = wrappedElement.type;
markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name);
console.time(markerName);
}
 **//*調(diào)用對(duì)應(yīng)ReactReconciler中的mountComponent方法來(lái)渲染組件,返回React組件解析后的HTML** 

var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context, 0 /* parentDebugID */);
if (markerName) {
console.timeEnd(markerName);
}
wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance;
 /*將解析出來(lái)的HTML插入DOM中 ReactMount._mountImageIntoNode</a> (markup, container, wrapperInstance, shouldReuseMarkup, transaction);

}

_mountImageIntoNode 可以實(shí)現(xiàn)將HTML插入DOM中的操作方法是:

_mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) {
/*是否復(fù)用markup
if (shouldReuseMarkup) {
/*如果可以復(fù)用,直接將instance插入到根元素** 
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
ReactDOMComponentTree.precacheNode(instance, rootElement);
return;
} else {
/*創(chuàng)建新的normalizedMarkup
var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
var rootMarkup = rootElement.outerHTML;
rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum);
var normalizedMarkup = markup;
if (process.env.NODE_ENV !== 'production') {
var normalizer;
if (container.nodeType === ELEMENT_NODE_TYPE) {
normalizer = document.createElement('div');
normalizer.innerHTML = markup;
normalizedMarkup = normalizer.innerHTML;
} else {
normalizer = document.createElement('iframe');
document.body.appendChild(normalizer);
normalizer.contentDocument.write(markup);
normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML;
document.body.removeChild(normalizer);
}
}
if (transaction.
while (container.lastChild) {
container.removeChild(container.lastChild);
}
DOMLazyTree.insertTreeBefore(container, markup, null);
} else {
/*利用innerHTML將markup插入到container這個(gè)DOM元素上** 
setInnerHTML(container, markup);
 /*將instance保存到container的原生節(jié)點(diǎn)firstChild上*/
ReactDOMComponentTree.precacheNode(instance, container.firstChild);
}
if (process.env.NODE_ENV !== 'production') {
var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
if (hostNode._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: hostNode._debugID,
type: 'mount',
payload: markup.toString()
});
}
}
}
};

這么多的內(nèi)容有點(diǎn)懵懵的,下面我們通過(guò)簡(jiǎn)單的流程圖總結(jié):


繪圖1.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,310評(píng)論 3 415
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,951評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,566評(píng)論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,055評(píng)論 1 322
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評(píng)論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,303評(píng)論 0 288
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,799評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,683評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,899評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,135評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評(píng)論 1 282
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,528評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,844評(píng)論 2 372

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

  • 原教程內(nèi)容詳見精益 React 學(xué)習(xí)指南,這只是我在學(xué)習(xí)過(guò)程中的一些閱讀筆記,個(gè)人覺得該教程講解深入淺出,比目前大...
    leonaxiong閱讀 2,849評(píng)論 1 18
  • 自己最近的項(xiàng)目是基于react的,于是讀了一遍react的文檔,做了一些記錄(除了REFERENCE部分還沒(méi)開始讀...
    潘逸飛閱讀 3,435評(píng)論 1 10
  • React Native是基于React的,在開發(fā)React Native過(guò)程中少不了的需要用到React方面的知...
    亓凡閱讀 1,487評(píng)論 1 4
  • 現(xiàn)在最熱門的前端框架,毫無(wú)疑問(wèn)是 React 。上周,基于 React 的 React Native 發(fā)布,結(jié)果一...
    sakura_L閱讀 436評(píng)論 0 0
  • 楊小蓮,白族女孩,前不久已成為女孩她媽了。初見小蓮,是大學(xué)報(bào)道第一天,似乎什么都變得不順利了當(dāng)爸爸說(shuō)他要回家的那一...
    燊兒閱讀 267評(píng)論 0 0