ReactJS分析之入口函数render

ReactJS分析之入口函数render

 

前言

在使用React进行构建应用时,我们总会有一个步骤将组建或者虚拟DOM元素渲染到真实的DOM上,将任务交给浏览器,进而进行layout和paint等步骤,这个函数就是React.render()。首先看下该函数的接口定义:

ReactComponent render( ReactElement element, DOMElement container, [function callback] )

接收2-3个参数,并返回ReactComponent类型的对象,当组件被添加到DOM中后,执行回调。在这里涉及到了两个React类型--ReactComponent和ReactElement,着重分析。

ReactElement类型解读

ReactElement类型通过函数React.createElement()创建,接口定义如下:

ReactElement createElement( string/ReactClass type, [object props], [children ...] )

第一个参数可以接受字符串(如“p”,“div”等HTML的tag)或ReactClass,第二个参数为传递的参数,第三个为子元素,可以为字符串和ReactElement。

下面着重分析createElement的具体实现:

ReactElement.createElement = function(type, config, children) {
var propName; // Reserved names are extracted
var props = {}; var key = null;
var ref = null; if (config != null) {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + config.key;
// Remaining properties are added to a new props object
for (propName in config) {
if (config.hasOwnProperty(propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
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;
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
} return new ReactElement(
type,
key,
ref,
ReactCurrentOwner.current,
ReactContext.current,
props
);
}; var ReactElement = function(type, key, ref, owner, context, props) {
// Built-in properties that belong on the element
this.type = type;
this.key = key;
this.ref = ref; // Record the component responsible for creating this element.
this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible
// through the owner.
this._context = context; if ("production" !== process.env.NODE_ENV) {
// The validation flag and props are currently mutative. We put them on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
try {
Object.defineProperty(this._store, 'validated', {
configurable: false,
enumerable: false,
writable: true
});
} catch (x) {
}
this._store.validated = false; // We're not allowed to set props directly on the object so we early
// return and rely on the prototype membrane to forward to the backing
// store.
if (useMutationMembrane) {
Object.freeze(this);
return;
}
} this.props = props;
};

在ReactElement.js中实现了该方法,首先保存传入的参数,其中ref和key这两个参数比较特别,ref用于父组件引用子组件的真实DOM,key用于调和算法,判断该组件是否update或remove;保存children到props中,并根据type是否有defaultProps属性对props进行mixin;最后创建ReactElement实例。其中reactElement有个实例属性_owner,用于保存所属的组件。

ReactElement的原型对象只有一个简单的方法用于判断是否是ReactElement对象,没有额外的方法。

综上,我们可以看出ReactElement有4个属性:type,ref,key,props,并且轻量,没有状态,是一个虚拟化的DOM元素。

ReactClass类型解读

React的核心是ReactElement类型,但是精髓确实ReactComponent,即组件。但是组件的创建却并不简单,我们通过React.createClass创建ReactClass类,它是ReactComponent的构造函数,不同于正常的对象创建,组件的创建由React接管,即我们无须对其实例化(new MyComponent())。相对于ReactElement的无状态,ReactComponent是有状态的,先看接口定义:

ReactClass createClass(object specification)

传入的spec参数必须包含render方法,用于渲染虚拟DOM,render返回ReactElement类型;另外还有一些getInitialState和生命周期方法,可以根据需要定义。

下面根据createClass的实现来深入分析:

createClass: function(spec) {
var Constructor = function(props, context) { // Wire up auto-binding
if (this.__reactAutoBindMap) {
bindAutoBindMethods(this);
} this.props = props;
this.context = context;
this.state = null; // ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor; injectedMixins.forEach(
mixSpecIntoComponent.bind(null, Constructor)
); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
} // Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
} // Legacy hook
Constructor.type = Constructor; return Constructor;
}
// Constructor的原型
var ReactClassComponent = function() {};
// assign类似于mixin
assign(
ReactClassComponent.prototype,
ReactComponent.prototype,
ReactClassMixin
); // mixin到Constructor的原型上
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
} var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
} for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
} if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above
continue;
} var property = spec[name];
validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod =
ReactClassInterface.hasOwnProperty(name);
var isAlreadyDefined = proto.hasOwnProperty(name);
var markedDontBind = property && property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isReactClassMethod &&
!isAlreadyDefined &&
!markedDontBind; if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name]; // For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("production" !== process.env.NODE_ENV) {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}

createClass返回一个Constructor构造函数,它的原型是new ReactClassComponent()对象,该对象有mixin的组件的方法(在spec对象中的mixins属性的对象的方法)和ReactComponent的方法(setState和forceUpdate),并且在mixSpecIntoComponent(Constructor, spec)方法中将spec中实现的方法绑定到Constructor的原型上,在这里对于非React提供的方法(即个人实现的一些功能函数或者事件处理函数)保存在原型的__reactAutoBindMap的属性上。最后再设置Constructor的defaultProps和type(Constructor.type = Constructor)。

在上节中提到了createElement的第一个参数可以是ReactClass,因此在Constructor实现上赋予了type和defaultProps属性。

React的入口—React.render()

React.render的实现是在ReactMount中,我们通过源码进行进一步的分析。

render: function(nextElement, container, callback) {

    var prevComponent = instancesByReactRootID[getReactRootID(container)];

    if (prevComponent) {
var prevElement = prevComponent._currentElement;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
return ReactMount._updateRootComponent(
prevComponent,
nextElement,
container,
callback
).getPublicInstance();
} else {
ReactMount.unmountComponentAtNode(container);
}
} var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup =
reactRootElement && ReactMount.isRenderedByReact(reactRootElement); var shouldReuseMarkup = containerHasReactMarkup && !prevComponent; var component = ReactMount._renderNewRootComponent(
nextElement,
container,
shouldReuseMarkup
).getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
}

如果是第一次挂载该ReactElement,直接添加即可;如果之前已挂载过,则通过instancesByReactRootID获取渲染之前container的旧组件,即prevComponent,具体通过获取container的firstChild,并根据缓存获取该对象对应的id,并根据id得到prevComponent。每个component对象都有对应的虚拟DOM,即ReactElement,通过shouldUpdateReactComponent(prevElement, nextElement)进行判断对组件进行update还是delete。

具体shouldUpdateReactComponent的比较算法是:如果prevElement类型为string或者number,那么nextElement类型为string或number时为true;如果prevElement和nextElement为object,并且key和type属性相同,则prevElement._owner == nextElement._owner相等时为true,否则为false。

如果需要更新,则调用ReactMount.._updateRootComponent函数进行Reconciliation,并返回该组件;否则删除该组件,具体操作则是删除container的所有子元素。然后判断shouldReuseMarkup,对于初次挂载的ReactElement而言,该标记为false。最后通过调用_renderNewRootComponent方法将ReactElement渲染到DOM上,并获取对应的ReactComponent对象,最后执行回调并返回组件对象。

对于_renderNewRootComponent方法,通过调用instantiateReactComponent(nextElement, null)来实例化组件,并在ReactMount的缓存中注册组件,批量执行更新ReactUpdates.batchedUpdates,最终通过_mountImageIntoNode方法将虚拟节点插入到DOM中。

至此,React中比较重要的方法讲解完毕。下一步计划是分析组件的实例化过程,敬请期待。

 
分类: Pure JS
标签: React

ReactJS-render的更多相关文章

  1. vue中的页面渲染方案

    一.模板渲染 <div id="J_render_app"> <ul v-if="items.length"> <li v-for ...

  2. ReactJS分析之入口函数render

    前言 在使用React进行构建应用时,我们总会有一个步骤将组建或者虚拟DOM元素渲染到真实的DOM上,将任务交给浏览器,进而进行layout和paint等步骤,这个函数就是React.render() ...

  3. ReactJs 报错 Element type is invalid: expected a string (from built-in components) or a class/function (for composite components) but got: undefined. Check the render method of `Me`.

    今天在重构一个页面的时候,碰到了一个error,具体的error信息如下图中所示: 最后经过一番查找定位,终于找到了问题所在,原因就是在父组件引用子组件时多加了一个大括号. import {Chart ...

  4. 一看就懂的ReactJs入门教程-精华版

    现在最热门的前端框架有AngularJS.React.Bootstrap等.自从接触了ReactJS,ReactJs的虚拟DOM(Virtual DOM)和组件化的开发深深的吸引了我,下面来跟我一起领 ...

  5. ReactJS webpack实现JS模块化使用的坑

    从一个原生HTML/CSS/JS模式的网页改造到ReactJS模块化的结构,需要以下步骤: (1)引用ReactJS框架 ->(2)使用webpack 工具 -> (3)配置webpack ...

  6. 初探ReactJS.NET 开发

    ReactJS通常也被称为"React",是一个刚刚在这场游戏中登场的新手.它由Facebook创建,并在2013年首次发布.Facebook认为React在处理SPA问题上可以成 ...

  7. 初识ReactJs(一)

    React的开发背景 ReactJS官网地址:http://facebook.github.io/react/ Github地址:https://github.com/facebook/react J ...

  8. D2.Reactjs 操作事件、状态改变、路由

    下面内容代码使用ES6语法 一.组件的操作事件: 1.先要在组件类定义内定义操作事件的方法,如同event handler.若我需要监听在组件内的Button的点击事件onClick,首先定义监听方法 ...

  9. D1.1.利用npm(webpack)构建基本reactJS项目

    前提: 已经安装nodejs和npm #全局安装webpack 自动构建化工具,职能管理项目:webpack-dev-server是开发工具,提供 Hot Module Replacement 功能# ...

  10. ReactJS实现的通用分页组件

    大家多少都自己写过各种版本的分页工具条吧,像纯服务版的,纯jsWeb板的,Angular版的,因为这个基础得不能再基础的功能太多地方都会用到,下面我给出以个用ReactJS实现的版本,首先上图看下效果 ...

随机推荐

  1. java编程接口(6) ------ 图标

    本文提出了自己的学习笔记,欢迎转载,但请注明出处:http://blog.csdn.net/jesson20121020 能够在JLable或者不论什么从AbstractButton继承的组件使用Ic ...

  2. hdu 4661 Message Passing(木DP&amp;组合数学)

    Message Passing Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Other ...

  3. skyeye安装+arm-elf-gdb安装+模拟s3c44b0x+执行ucos4skyeye

    [假设你要引用.请阅读所有,这里是我的为期两天的过程只是一个记录] skyeye安装:ubuntu12.0432 llvm2.8 skyeye1.3.3 http://blog.chinaunix.n ...

  4. 【Linux探索之旅】第一部分第四课:磁盘分区,并完成Ubuntu安装

    内容简介 1.第一部分第四课:磁盘分区,并完成Ubuntu安装 2.第一部分第五课预告:Unity桌面,人生若只如初见 磁盘分区 上一课我们正式开始安装Ubuntu了,但是到了分区的那一步,小编却戛然 ...

  5. Swing动画之游戏角色

    一.动画效果:实现了飞机飞行的动画效果,也实现了飞机的移动. 二.实现原理: 1.飞机飞行 的效果:事实上也还是重写paintComponent,依照一定的时间间隔更换图片就有了飞行的效果,动画就是更 ...

  6. OnWndMsg处理功能

    于MFC于, OnWndMsg功能,如以下处理步骤: 1)首先.被推断消息有一个消息响应函数.例如OnLButtonDown()处理"左新闻"新闻. 2)数.这里以MFC 的pro ...

  7. HDU 2063:过山车(偶匹配,匈牙利算法)

    过山车 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submis ...

  8. 妙用perfmon Alert抓dump

    抓dump文件,经常是解决众多疑难杂症的不二手段.但是很多时候,我们没办法抓.比如说 几秒内的线程数暴涨200个,然后迅速回落 程序跑了两天,内存涨到某个数字就自己OOM了 原因不外乎都是时间短,没有 ...

  9. iOS6之后 NSAttributedString 福利

    @于iOS6之前,需要使用NSMutableAttributedString当你需要导入:CoreText.framework框架的.但在iOS6 之后就不在须要了. - (void)testOfNS ...

  10. 2014 I/O返回:Google连接一切

    文/蒋涛 6月.WWDC 2014与Google I/O  (大部分演讲视频都公开.Youtube须要FQ.很值得一看)相继召开. 今年是我第三年參加Google I/O大会.三年间,Google积累 ...