React原始碼解析(一):JSX到javascript

jiangzhifeng發表於2019-04-03

使用jsx可以寫類似html的標籤,通過宣告一個html標籤,然後呢會返回一個react內識別的物件,如下:

babel轉化前

<div id="div" className="div" key="div">
  <div>
    <span>2</span>
  </div>
  <span>1</span>
  <span>1</span>
</div>複製程式碼

轉化後

"use strict";

React.createElement("div", {
    id: "div",
    className: "div",
    key: "div"
  }, 
  React.createElement("div", null, React.createElement("span", null, "2")), 
  React.createElement("span", null, "1"), React.createElement("span", null, "1")
);複製程式碼

元件的轉化

function Comp() {
	return <div>111</div>
}

<Comp id="div" className="div" key="div">
  <span>222</span>
  <span>222</span>
</Comp>

-----------------------------------------------------------------------------------

function comp() {
	return <div>111</div>
}

<comp id="div" className="div" key="div">
  <span>222</span>
  <span>222</span>
</comp>
複製程式碼

轉化後

"use strict";

function Comp() {
  return React.createElement("div", null, "111");
}

React.createElement(Comp, {
    id: "div",
    className: "div",
    key: "div"
  }, 
  React.createElement("span", null, "222"), 
  React.createElement("span", null, "222")
);

-----------------------------------------------------------------------------------
"use strict";

function comp() {
  return React.createElement("div", null, "111");
}

React.createElement('comp', {
    id: "div",
    className: "div",
    key: "div"
  }, 
  React.createElement("span", null, "222"), 
  React.createElement("span", null, "222")
);複製程式碼

注意:從上面的例子我們可以看到這就是為什麼要求我們元件要首字母大寫,因為小寫它會當做一個標籤來處理,最後會轉化成一個字串,然後如果沒有這個標籤就會報錯。


相關文章