React源碼解析之React.createElement()

在第一次學(xué)習(xí)react的時候,我們總會帶著許多疑問。比如我們看到下面的代碼就會想:為什么我們只是引入了React,但是并沒有明顯的看到我們在其他地方用,這時我們就會想著既然沒有用到,那如果刪除之后會不會受到影響呢?答案當(dāng)然是不行的。

import React from 'react';
import ReactDOM from 'react-dom';

let element = (
    <h1 id="title" className="bg" style={{color: 'red'}}>
        hello
        <span>world</span>
    </h1>
)

console.log({type: element.type, props:element.props})

ReactDOM.render(element,document.getElementById('root'));

當(dāng)我們帶著這個問題去研究的時候會發(fā)現(xiàn)其實在渲染element的時候調(diào)了React.createElement(),所以上面的問題就在這里找到了答案。

那么React.createElement()到底干了些什么事情呢?

  1. 我們看一看下面的代碼
<h1 id="title" className="bg" style={{color: 'red'}}>
        hello
        <span>world</span>
</h1>

//上面的這段代碼很簡單,但是我們都知道react是所謂的虛擬dom,當(dāng)然不可能就是我們看到的這樣。當(dāng)我們將上面的代碼經(jīng)過babel轉(zhuǎn)譯后,我們再看看

React.createElement("h1", {
  id: "title",
  className: "bg",
  style: {
    color: 'red'
  }
}, "hello", React.createElement("span", null, "world"));

  1. 那到底React.createElement干了些什么呢?
//方法接受三個參數(shù),第一個參數(shù)是組件類型,第二個參數(shù)是要傳遞給組件的屬性,第三個參數(shù)是children。方法最終會返回一個具有以下屬性的對象

function createElement(type,config,children){
    let propName;
    const props = {};
    for(propName in config){
        props[propName] = config[propName]
    }
    const childrenLength = arguments.length - 2;   //減掉type config  看看后面還有幾個兒子
    if(childrenLength === 1){
        props.children = children;
    }else if(childrenLength > 1){  //如果說兒子的數(shù)量大于1的話,props.children就是一個數(shù)組
        props.children = Array.from(arguments).slice(2)
    }
    return {type,props}
}

export default {
    createElement
}


/**
React.createElement("h1", {
  id: "title",
  className: "bg",
  style: {
    color: 'red'
  }
}, "hello", React.createElement("span", null, "world"));
 */

最后我們看到React通過createElement方法將組件或者元素轉(zhuǎn)成ReactElement,并最終通過一系列操作渲染到頁面成為HTMLElement。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容