React源碼分析

組件是什麼樣的?

下面是一個簡單的組件 打印一下這個組件,發現實際上是一個js對象,而不是真實的dom。 那麼react是如何將react組件生成js對象的呢? 這是由於咱們在建立組件的時候,使用了extends.React.Component,即繼承了Component,看下Component的源碼react

function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.setState = function (partialState, callback) {}
Component.prototype.forceUpdate = function (callback) {}
複製代碼

咱們聲明瞭一個組件,繼承了Component,它的原型上有setState等方法。 小結bash

組件初始化

咱們在react類和咱們平時寫的js類都同樣,惟一的區別在與react類多了一個render()方法,輸出相似「這是A組件」的結構並掛載到真實DOM上,才能觸發組件的生命週期併成爲DOM樹的一部分。 首先咱們看下render()方法dom

發現render()實際是是調用一個React.creatEment('div',null),實際是實際是ReactElement方法 這個方法的做用是:每個組件的對象都是經過React.creatEment()建立出來的ReactElement類型的對象,ReactElement對象記錄了組件的特徵,好比key,type,ref,props等,這些特徵與渲染成頁面息息相關。 下圖是ReactElement方法源碼:

小結

組件的掛載

咱們知道react是經過ReactDOM.render(component,monutNode)的形式進行掛載的(能夠掛載自定義組件,原生dom,字符串) 掛載過程是怎麼樣的呢?oop

ReactDOM.render實際調用了內部的ReactMount.render,進而執行ReactMount._renderSubtreeIntoContainer。從字面意思上就能夠看出是將"子DOM"插入容器的邏輯,咱們看下源碼實現:ui

render: function (element, container, callback) {
    return renderSubtreeIntoContainer(null, element, container, false, callback);
  },
  function renderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback){}
複製代碼

咱們看下renderSubtreeIntoContainer的入參:this

parentComponent:當前組件的父組件,第一次渲染時爲null children:要插入DOM中的組件,如helloWorld container:要插入的容器,如document.getElementById('root')spa

小結

組件的生命週期

咱們知道,根據ReactDOM.render()的入參類型不一樣,在內部經過工廠方法生成四種不一樣類型的封裝組件:prototype

ReactEmptyComponent(空對象)3d

ReactTextComponent(字符串)code

ReactDOMComponent(原生dom)

ReactCompositeComponent(自定義組件,這個類型纔會有生命週期)

在執行掛載流程時,經過執行每種封裝組件內部的mountComponent方法觸發生命週期,但顯然生命週期只在React自定義組件中存在,也就是ReactCompositeComponent。

小結

相關文章
相關標籤/搜索