? ?? ?在介紹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è)功能:
- 調(diào)用React.createElement生成待插入節(jié)點(diǎn)的虛擬DOM的實(shí)例對(duì)象(上篇文章中已經(jīng)講到,這里就不再重復(fù)敘述)
- 與之前的component比較,如果是初次渲染直接將虛擬DOM轉(zhuǎn)換為真實(shí)DOM
- 將真實(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é):