React.js核心原理实现:首次渲染机制

前端之家收集整理的这篇文章主要介绍了React.js核心原理实现:首次渲染机制前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、前言

react.js和vue.js无疑是当下最火的js框架了,它们为组件式的开发传统前端页面、SPA页面、前后端分离等带来了有力的支持。react.js源码实现较为复杂(据说FaceBook的react团队目前正在全面重写react实现),如果直接通过阅读react源码理解其原理还是比较有难度的,因此,通过把react核心概念自己手动实现一遍,那么既可以避开react源码的复杂性又可以加深自己的理解。其实,react核心概念并不多:

  • 虚拟dom对象(Virtual DOM)
  • 虚拟dom差异化算法(diff algorithm)
  • 单向数据流渲染(Data Flow)
  • 组件生命周期
  • 事件处理

声明:

  • 本文假定你已经对reactjs有了一定的了解,如果没有至少看下ruanyifeng老师的入门demo
  • jsx不在本文的讨论范围,所有的例子原理都是使用原生的javascript。
  • 篇幅限制,服务器端的reactjs也不在本文讨论范围内(服务端渲染)。
  • 为了演示方便,本文以jQuery作为基本工具库。
  • 为了更清晰的演示原理,本文会忽略很多细节的东西,千万不要用于生产环境。

所有实例源码都托管在github。点这里里面有分步骤的例子,可以一边看一边运行例子。

二、入门实例

以向div渲染一个“hello world”文本开始:

  1. <script type="text/javascript">
  2. React.render('hello world',document.getElementById("container"))
  3. </script>
  4.  
  5. <div id="container"></div>
  6.  
  7. /**
  8. 生成后的html为:
  9.  
  10. <div id="container">
  11. <span data-reactid="0">hello world</span>
  12. </div>
  13.  
  14. */

可以看到,上面最关键的代码就是:React.render,下面看其实现:

  1. // component类,用来表示文本在渲染,更新,删除时应该做些什么事情
  2. function ReactDOMTextComponent(text) {
  3. // 存下当前的字符串(该component绑定的element)
  4. this._currentElement = '' + text;
  5. // 用来标识当前component的Id
  6. this._rootNodeID = null;
  7. }
  8.  
  9. // component渲染时生成的dom结构
  10. ReactDOMTextComponent.prototype.mountComponent = function(rootID) {
  11. this._rootNodeID = rootID;
  12. // 生成dom
  13. return '<span data-reactid="' + rootID + '">' + this._currentElement + '</span>';
  14. }
  15.  
  16.  
  17. // component工厂 用来根据element类型返回一个相应的component实例
  18. function instantiateReactComponent(node){
  19. // 如果传进来的node是字符串或者是一个数值
  20. if(typeof node === 'string' || typeof node === 'number'){
  21. // 就创建并返回一个文本component
  22. return new ReactDOMTextComponent(node)
  23. }
  24. }
  25.  
  26.  
  27. React = {
  28. nextReactRootIndex:0,render:function(element,container){
  29. // 根据element返回一个component
  30. var componentInstance = instantiateReactComponent(element);
  31. // 渲染生成dom结构
  32. var markup = componentInstance.mountComponent(React.nextReactRootIndex++);
  33. // 插入到容器中
  34. $(container).html(markup);
  35. // 触发完成mount的事件
  36. $(document).trigger('mountReady'); }
  37. }

代码主要分为三个部分:

1、React.render 作为渲染的入口

2、引入了component类的概念,ReactDOMTextComponent是一个component类定义,它是一个文本类型的component。component提供了在渲染,更新,删除时应该对element做什么操作,由于目前只用到渲染,另外两个可以先忽略。

3、instantiateReactComponent用来根据element的类型(现在只有一种string类型),返回一个component的实例。其实就是个类工厂。

nextReactRootIndex作为每个component的标识id,不断加1,确保唯一性。这样我们以后可以通过这个标识找到这个元素。

可以看到我们把逻辑分为几个部分,主要的渲染逻辑放在了具体的componet类去定义(只有component自己最清楚如何渲染自己)。React.render负责调度整个流程,这里是调用instantiateReactComponent生成一个对应component类型的实例对象,然后调用此对象的mountComponent获取生成内容(dom结构)。最后插入到对应的container节点中。

插播:上面的代码使用了javascript原型链,不熟悉原型链的可以看下面这张图:

三、基本元素类型element

reactjs最大的卖点就是它的虚拟dom概念,一般使用React.createElement来创建一个虚拟dom元素。虚拟dom元素分为两种,一种是浏览器自带基本元素比如 div p input form 这种,一种是自定义的元素。理论上文本节点不算虚拟dom,但是reac.js为了保持渲染的一致性,在文本节点外面包了一层span标记,也给它配了个简化版component(ReactDOMTextComponent)。

本节只讨论基本元素(element)。

在reactjs里,当我们希望在hello world外面包一层div,并且带上一些属性,甚至事件时我们可以这么写:

  1. //演示事件监听怎么用
  2. function hello(){
  3. alert('hello')
  4. }
  5.  
  6. // 创建一个基本元素element
  7. var element = React.createElement('div',{id:'test',onclick:hello},'click me')
  8.  
  9. React.render(element,document.getElementById("container"))
  10.  
  11.  
  12. /**
  13.  
  14. 生成的html为:
  15.  
  16. <div data-reactid="0" id="test">
  17. <span data-reactid="0.0">click me</span>
  18. </div>
  19.  
  20.  
  21. 点击文字,会弹出hello的对话框
  22.  
  23. */

上面使用React.createElement创建了一个基本元素,下面来看看简易版本React.createElement的实现:

  1. //ReactElement就是虚拟dom的概念,具有一个type属性代表当前的节点类型,还有节点的属性props
  2. //比如对于div这样的节点type就是div,props就是那些attributes
  3. //另外这里的key,可以用来标识这个element,用于优化以后的更新,这里可以先不管,知道有这么个东西就好了
  4. function ReactElement(type,key,props){
  5. this.type = type;
  6. this.key = key;
  7. this.props = props;
  8. }
  9.  
  10.  
  11. React = {
  12. nextReactRootIndex:0,// createElement函数定义
  13. createElement:function(type,config,children){
  14. var props = {},propName;
  15. config = config || {}
  16. // 看有没有key,用来标识element的类型,方便以后高效的更新,这里可以先不管
  17. var key = config.key || null;
  18.  
  19. // 复制config里的内容到props
  20. for (propName in config) {
  21. if (config.hasOwnProperty(propName) && propName !== 'key') {
  22. props[propName] = config[propName];
  23. }
  24. }
  25.  
  26. // 处理children,全部挂载到props的children属性
  27. // 支持两种写法,如果只有一个参数,直接赋值给children,否则做合并处理
  28. var childrenLength = arguments.length - 2;
  29. if (childrenLength === 1) {
  30. props.children = $.isArray(children) ? children : [children] ;
  31. } else if (childrenLength > 1) {
  32. var childArray = Array(childrenLength);
  33. for (var i = 0; i < childrenLength; i++) {
  34. childArray[i] = arguments[i + 2];
  35. }
  36. props.children = childArray;
  37. }
  38.  
  39. // 创建新的ReactElement
  40. return new ReactElement(type,props);
  41.  
  42. },container){
  43. var componentInstance = instantiateReactComponent(element);
  44. var markup = componentInstance.mountComponent(React.nextReactRootIndex++);
  45. $(container).html(markup);
  46. //触发完成mount的事件
  47. $(document).trigger('mountReady');
  48. }
  49. }

createElement只是做了简单的参数修正,最终返回一个ReactElement实例对象也就是我们说的虚拟元素的实例。这里注意key的定义,主要是为了以后更新时优化效率,这边可以先不管忽略。

有了元素实例,得把他渲染出来,此时render接受的是一个ReactElement而不是文本,先改造下instantiateReactComponent:

  1. function instantiateReactComponent(node){
  2. //文本节点的情况
  3. if(typeof node === 'string' || typeof node === 'number'){
  4. return new ReactDOMTextComponent(node);
  5. }
  6. //浏览器基本element,注意基本类型element的type一定是字符串,可以和自定义element时对比
  7. if(typeof node === 'object' && typeof node.type === 'string'){
  8. //注意这里,使用了一种新的component
  9. return new ReactDOMComponent(node);
  10. }
  11. }

这里增加了一个判断,这样当render的不是文本而是浏览器的基本元素时。就使用另外一种component(ReactDOMComponent)来处理它渲染时应该返回的内容。这里就体现了工厂方法instantiateReactComponent的好处了,不管来了什么类型的node,都可以负责生产出一个负责渲染的component实例。这样render完全不需要做任何修改,只需要再做一种对应的component类型(这里是ReactDOMComponent)就行了。

所以重点我们来看看ReactDOMComponent的具体实现:

  1. //component类,用来表示文本在渲染,更新,删除时应该做些什么事情
  2. function ReactDOMComponent(element){
  3. //存下当前的element对象引用
  4. this._currentElement = element;
  5. this._rootNodeID = null;
  6. }
  7.  
  8. //component渲染时生成的dom结构
  9. ReactDOMComponent.prototype.mountComponent = function(rootID){
  10. // 标识
  11. this._rootNodeID = rootID;
  12. // element属性
  13. var props = this._currentElement.props;
  14. // 开始构造dom结构的开始和结束标签
  15. var tagOpen = '<' + this._currentElement.type;
  16. var tagClose = '</' + this._currentElement.type + '>';
  17.  
  18. // 加上reactid标识,reactid=_rootNodeID
  19. tagOpen += ' data-reactid=' + this._rootNodeID;
  20.  
  21. // 拼凑出属性
  22. for (var propKey in props) {
  23. // 这里要做一下事件的监听,就是从属性props里面解析拿出on开头的事件属性的对应事件监听
  24. if (/^on[A-Za-z]/.test(propKey)) {
  25. // 事件类型
  26. var eventType = propKey.replace('on','');
  27. // 针对当前的节点添加事件代理,代理了reactid=_rootNodeID子节点的事件
  28. $(document).delegate('[data-reactid="' + this._rootNodeID + '"]',eventType + '.' + this._rootNodeID,props[propKey]);
  29. }
  30.  
  31. // 对于children属性以及事件属性不需要进行字符串拼接
  32. // 事件会代理到全局。这边不能拼到dom上不然会产生原生的事件监听
  33. // children属性会在下面递归处理
  34. if (props[propKey] && propKey != 'children' && !/^on[A-Za-z]/.test(propKey)) {
  35. tagOpen += ' ' + propKey + '=' + props[propKey];
  36. }
  37. }
  38. // 获取子节点渲染出的内容
  39. var content = '';
  40. var children = props.children || [];
  41. // 用于保存所有的子节点的componet实例,以后会用到
  42. var childrenInstances = [];
  43. var that = this;
  44. $.each(children,function(key,child) {
  45. // 这里再次调用了instantiateReactComponent实例化子节点component类,拼接好返回
  46. var childComponentInstance = instantiateReactComponent(child);
  47. childComponentInstance._mountIndex = key;
  48. // 将子节点实例缓存到childrenInstances
  49. childrenInstances.push(childComponentInstance);
  50. // 子节点的rootId是父节点的rootId加上新的key也就是顺序的值拼成的新值
  51. var curRootId = that._rootNodeID + '.' + key;
  52. // 得到子节点的渲染内容
  53. var childMarkup = childComponentInstance.mountComponent(curRootId);
  54. // 拼接在一起
  55. content += ' ' + childMarkup;
  56. })
  57.  
  58. // 留给以后更新时用的这边先不用管
  59. this._renderedChildren = childrenInstances;
  60.  
  61. // 拼出整个html内容
  62. return tagOpen + '>' + content + tagClose;
  63. }

增加了虚拟dom reactElement的定义,增加了一个新的componet类ReactDOMComponent。这样我们就实现了渲染浏览器基本元素的功能了。

对于虚拟dom的渲染逻辑,本质上是使用了递归,reactElement会递归渲染自己的子节点。可以看到我们通过instantiateReactComponent屏蔽了子节点的差异,只需要使用不同的componet类,这样都能保证通过mountComponent最终拿到渲染后的内容

另外这边的事件也要说下,可以在传递props的时候传入{onClick:function(){}}这样的参数,这样就会在当前元素上添加事件,代理到document。由于reactjs本身全是在写js,所以监听的函数的传递变得特别简单。

这里很多东西没有考虑,比如一些特殊的类型input select等等,再比如img不需要有对应的tagClose等。这里为了保持简单就不再扩展了。另外reactjs的事件处理其实很复杂,实现了一套标准的w3c事件。这里偷懒直接使用jQuery的事件代理到document上了。

四、自定义类型element

本节来看看自定义类型element的渲染原理。

下面先来看看在React中如何定义一个自定义元素element:

  1. // 自定义元素element
  2. var HelloMessage = React.createClass({
  3. // 初始状态
  4. getInitialState: function() {
  5. return {type: 'say:'};
  6. },// 生命周期:将要挂载时调用
  7. componentWillMount: function() {
  8. console.log('我就要开始渲染了。。。')
  9. },// 生命周期:已经挂载之后调用
  10. componentDidMount: function() {
  11. console.log('我已经渲染好了。。。')
  12. },// 渲染并返回一个虚拟dom(包括element和text)
  13. render: function() {
  14. return React.createElement("div",null,this.state.type,"Hello ",this.props.name);
  15. }
  16. });
  17.  
  18.  
  19. React.render(React.createElement(HelloMessage,{name: "John"}),document.getElementById("container"));
  20.  
  21. /**
  22. 结果为:
  23.  
  24. html:
  25. <div data-reactid="0">
  26. <span data-reactid="0.0">say:</span>
  27. <span data-reactid="0.1">Hello </span>
  28. <span data-reactid="0.2">John</span>
  29. </div>
  30.  
  31. console:
  32. 我就要开始渲染了。。。
  33. 我已经渲染好了。。。
  34.  
  35. */

可以看到,这里的createElement函数第一个参数的类型不再是字符串,而是一个class,

React.createClass生成一个自定义标记类,带有基本的生命周期:

  • getInitialState :获取最初的属性值this.state
  • componentWillmount :在组件准备渲染时调用
  • componentDidMount :在组件渲染完成后调用

下面就来看看React.createClass的实现吧:

  1. // 定义ReactClass类,所有自定义的超级父类
  2. var ReactClass = function(){
  3. }
  4. // 留给子类去继承覆盖
  5. ReactClass.prototype.render = function(){}
  6.  
  7.  
  8.  
  9. React = {
  10. nextReactRootIndex:0,// 创建自定义
  11. createClass:function(spec){
  12. // 生成一个子类
  13. var Constructor = function (props) {
  14. this.props = props;
  15. this.state = this.getInitialState ? this.getInitialState() : null;
  16. }
  17. // 原型继承,继承超级父类
  18. Constructor.prototype = new ReactClass();
  19. Constructor.prototype.constructor = Constructor;
  20. // 混入spec到原型
  21. $.extend(Constructor.prototype,spec);
  22. return Constructor;
  23.  
  24. },createElement:function(type,children){
  25. ...
  26. },container){
  27. ...
  28. }
  29. }

可以看到createClass生成了一个继承ReactClass的子类,在构造函数调用this.getInitialState获得最初的state。

为了演示方便,我们这边的ReactClass相当简单,实际上原始的代码处理了很多东西,比如类的mixin的组合继承支持,比如componentDidMount等可以定义多次,需要合并调用等等,有兴趣的去翻源码吧,不是本文的主要目的,这里就不详细展开了。

我们这里只是返回了一个继承类的定义,那么具体的componentWillmount,这些生命周期函数在哪里调用呢。

看看我们上面的两种类型就知道,我们是时候为自定义元素也提供一个componet类了,在那个类里我们会实例化ReactClass,并且管理生命周期,还有父子组件依赖。

好,我们老规矩先改造instantiateReactComponent

  1. function instantiateReactComponent(node){
  2. // 文本节点的情况
  3. if(typeof node === 'string' || typeof node === 'number'){
  4. return new ReactDOMTextComponent(node);
  5. }
  6. // 浏览器默认节点的情况
  7. if(typeof node === 'object' && typeof node.type === 'string'){
  8. //注意这里,使用了一种新的component
  9. return new ReactDOMComponent(node);
  10.  
  11. }
  12. // 自定义的元素节点,类型为构造函数
  13. if(typeof node === 'object' && typeof node.type === 'function'){
  14. // 注意这里,使用新的component,专门针对自定义元素
  15. return new ReactCompositeComponent(node);
  16.  
  17. }
  18. }

很简单我们增加了一个判断,使用新的component类形来处理自定义的节点。我们看下ReactCompositeComponent的具体实现:

  1. function ReactCompositeComponent(element){
  2. //存放元素element对象
  3. this._currentElement = element;
  4. //存放唯一标识
  5. this._rootNodeID = null;
  6. //存放对应的ReactClass的实例
  7. this._instance = null;
  8. }
  9.  
  10. //用于返回当前自定义元素渲染时应该返回的内容
  11. ReactCompositeComponent.prototype.mountComponent = function(rootID){
  12. this._rootNodeID = rootID;
  13. //拿到当前元素对应的属性
  14. var publicProps = this._currentElement.props;
  15. //拿到对应的ReactClass
  16. var ReactClass = this._currentElement.type;
  17. // Initialize the public class
  18. var inst = new ReactClass(publicProps);
  19. this._instance = inst;
  20. //保留对当前comonent的引用,下面更新会用到
  21. inst._reactInternalInstance = this;
  22.  
  23. // 如果自定义元素设置了componentWillMount生命周期
  24. if (inst.componentWillMount) {
  25. inst.componentWillMount();
  26. //这里在原始的reactjs其实还有一层处理,就是 componentWillMount调用setstate,不会触发rerender而是自动提前合并,这里为了保持简单,就略去了
  27. }
  28. //调用ReactClass的实例的render方法,返回一个element或者一个文本节点
  29. var renderedElement = this._instance.render();
  30. //得到renderedElement对应的component类实例
  31. var renderedComponentInstance = instantiateReactComponent(renderedElement);
  32. this._renderedComponent = renderedComponentInstance; //存起来留作后用
  33.  
  34. //拿到渲染之后的字符串内容,将当前的_rootNodeID传给render出的节点
  35. var renderedMarkup = renderedComponentInstance.mountComponent(this._rootNodeID);
  36.  
  37. //之前我们在React.render方法最后触发了mountReady事件,所以这里可以监听,在渲染完成后会触发。
  38. $(document).on('mountReady',function() {
  39. //调用inst.componentDidMount
  40. inst.componentDidMount && inst.componentDidMount();
  41. });
  42.  
  43. return renderedMarkup;
  44. }

实现并不难,ReactClass的render一定是返回一个虚拟节点(包括element和text),这个时候我们使用instantiateReactComponent去得到实例,再使用mountComponent拿到结果作为当前自定义元素的结果。

应该说本身自定义元素不负责具体的内容,他更多的是负责生命周期。具体的内容是由它的render方法返回的虚拟节点来负责渲染的。

本质上也是递归的去渲染内容的过程。同时因为这种递归的特性,父组件的componentWillMount一定在某个子组件的componentWillMount之前调用,而父组件的componentDidMount肯定在子组件之后,因为监听mountReady事件,肯定是子组件先监听的。

需要注意的是自定义元素并不会处理我们createElement时传入的子节点,它只会处理自己render返回的节点作为自己的子节点。不过我们在render时可以使用this.props.children拿到那些传入的子节点,可以自己处理。其实有点类似webcomponents里面的shadow dom的作用。

上面实现了三种类型的元素,其实我们发现本质上没有太大的区别,都是有自己对应component类来处理自己的渲染过程。

本文源码实现以及参考内容来自于: http://purplebamboo.github.io/2015/09/15/reactjs_source_analyze_part_one/

猜你在找的React相关文章