【React源码解读】JSX到JavaScript的转换

JSX到JS的转化

https://babeljs.io/repl 代码转换jsx -> js

1).

<div></div>


React.createElement("div", null)

2).

<div id="div">test</div>


React.createElement("div", { id:"div" }, "test")

3).

<div id="div">
	<span>1</span>
  	<span>1</span>
</div>


React.createElement("div", {
  id: "div"
}, React.createElement("span", null, "1"), React.createElement("span", null, "1"));

4). 组件大小写区别

目前babel插件是根据首字母是否大小写,来判断是否字符串或者组件,自定义组件一定要写成大写,为什么要这样做?

// 大写
function Comp() {
	return <a>123</a>
}

<Comp id="div">
	<span>1</span>
  	<span>1</span>
</Comp>


"use strict";

function Comp() {
  return React.createElement("a", null, "123");
}

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

// 小写
function comp() {
	return <a>123</a>
}

<comp id="div">
	<span>1</span>
  	<span>1</span>
</comp>


"use strict";

function comp() {
  return React.createElement("a", null, "123");
}

React.createElement("comp", {
  id: "div"
}, React.createElement("span", null, "1"), React.createElement("span", null, "1"));
posted @ 2019-10-20 20:04  林璡  阅读(345)  评论(0编辑  收藏  举报