這個(gè)系列的目的是通過使用 JS 實(shí)現(xiàn)“乞丐版”的 React军俊,讓讀者了解 React 的基本工作原理,體會(huì) React 帶來的構(gòu)建應(yīng)用的優(yōu)勢
1 HTML 構(gòu)建靜態(tài)頁面
使用 HTML 和 CSS慢宗,我們很容易可以構(gòu)建出上圖中的頁面
<!DOCTYPE html>
<html lang="en">
<head>
<title>Build my react</title>
<style>
div {
text-align: center;
}
.father {
display: flex;
flex-direction: column;
justify-content: center;
height: 500px;
background-color: #282c34;
font-size: 30px;
font-weight: 700;
color: #61dafb;
}
.child {
color: #fff;
font-size: 16px;
font-weight: 200;
}
</style>
</head>
<body>
<div class="father">
Fucking React
<div class="child">用于構(gòu)建用戶界面的 JavaScript 庫</div>
</div>
</body>
</html>
當(dāng)然這只是一個(gè)靜態(tài)的頁面虽抄,我們知道脸侥,網(wǎng)站中最重要的活動(dòng)之一是和用戶產(chǎn)生交互,用戶通過觸發(fā)事件來讓網(wǎng)頁產(chǎn)生變化扇住,這時(shí)就需要用到 JS
2 DOM 構(gòu)建頁面
使用 DOM 操作春缕,我們也可以構(gòu)建上面的靜態(tài)頁面,并且可以動(dòng)態(tài)地改變頁面艘蹋、添加事件監(jiān)聽等來讓網(wǎng)頁活動(dòng)變得更加豐富
我們先改寫一下 HTML 的 body(如果沒有特殊說明锄贼,本文不會(huì)更改 CSS 的內(nèi)容),我們將 body 中的內(nèi)容都去掉簿训,新增一個(gè) id 為 root 都 div 標(biāo)簽咱娶,并且引入index.js
。
<div id="root"></div>
<script src="./index.js"></script>
index.js
內(nèi)容如下:
const text = document.createTextNode("Fucking React");
const childText = document.createTextNode("用于構(gòu)建用戶界面的 JavaScript 庫");
const child = document.createElement("div");
child.className = "child";
child.appendChild(childText);
const father = document.createElement("div");
father.className = "father";
father.appendChild(text);
father.appendChild(child);
const container = document.getElementById("root");
container.appendChild(father);
使用 DOM 操作强品,我們也可以構(gòu)建出同樣的頁面內(nèi)容膘侮,但是缺點(diǎn)很明顯
<div class="father">
Fucking React
<div class="child">用于構(gòu)建用戶界面的 JavaScript 庫</div>
</div>
原本只要寥寥幾行 HTML 的頁面。使用 DOM 之后的榛,為了描述元素的嵌套關(guān)系琼了、屬性、內(nèi)容等夫晌,代碼量驟增雕薪,并且可讀性非常差。這就是命令式編程晓淀,我們需要一步一步地指揮計(jì)算機(jī)去做事
這還只是一個(gè)簡單的靜態(tài)頁面所袁,沒有任何交互,試想一下凶掰,如果一個(gè)非常復(fù)雜的網(wǎng)頁都是用 DOM 來構(gòu)建燥爷,不好意思蜈亩,我不想努力了~
3 從命令式到聲明式
觀察上述 index.js
,我們不難發(fā)現(xiàn)前翎,在創(chuàng)建每個(gè)節(jié)點(diǎn)的時(shí)候其實(shí)可以抽象出一組重復(fù)操作:
- 根據(jù)類型創(chuàng)建元素
- 添加元素屬性(如 className)
- 逐一添加子元素
對(duì)于元素的嵌套關(guān)系和自身屬性稚配,我們可以利用對(duì)象來描述
const appElement = {
type: "div",
props: {
className: "father",
children: [
{
type: "TEXT",
props: {
nodeValue: "Fucking React",
children: [],
},
},
{
type: "div",
props: {
className: "child",
children: [
{
type: "TEXT",
props: {
nodeValue: "用于構(gòu)建用戶界面的 JavaScript 庫",
children: [],
},
},
],
},
},
],
},
};
其中,type
表示元素類型港华,特殊地道川,對(duì)于字符串文本,我們用TEXT
表示立宜;props
對(duì)象用來描述元素自身的屬性冒萄,比如 CSS 類名、children 子元素赘理、nodeValue
我們將頁面中的元素用 JS 對(duì)象來描述宦言,天然地形成了一種樹狀結(jié)構(gòu),接著利用遞歸遍歷對(duì)象就可以將重復(fù)的 DOM 操作去除商模,我們構(gòu)建如下 render 函數(shù)來將上述 JS 對(duì)象渲染到頁面上:
const render = (element, container) => {
const dom =
element.type == "TEXT"
? document.createTextNode("")
: document.createElement(element.type);
Object.keys(element.props)
.filter((key) => key !== "children")
.forEach((prop) => (dom[prop] = element.props[prop]));
element.props.children.forEach((child) => render(child, dom));
container.appendChild(dom);
};
調(diào)用 render 函數(shù):
render(appElement, document.getElementById("root"));
現(xiàn)在我們只需要將我們想要的頁面結(jié)構(gòu)通過 JS 對(duì)象描述出來,然后調(diào)用 render 函數(shù)蜘澜,JS 就會(huì)幫我們將頁面渲染出來施流,而無需一步步地書寫每一步操作
這就是聲明式編程,我們需要做的是描述目標(biāo)的性質(zhì)鄙信,讓計(jì)算機(jī)明白目標(biāo)瞪醋,而非流程。
對(duì)比命令式和聲明式編程装诡,體會(huì)兩者的區(qū)別
4 JSX
對(duì)比 JS 對(duì)象和 HTML银受,JS 對(duì)象的可讀性還是不行,所以 React 引入了 JSX 這種 JavaScript 的語法擴(kuò)展
我們的 appElement 變成了這樣:
// jsx
const appElement = (
<div className="father">
Fucking React
<div className="child">"用于構(gòu)建用戶界面的 JavaScript 庫"</div>
</div>
);
現(xiàn)在描述元素是不是變得超級(jí)爽鸦采!
然而這玩意兒 JS 并不認(rèn)識(shí)宾巍,所以我們還得把這玩意兒解析成 JS 能認(rèn)識(shí)的語法,解析不是本文的重點(diǎn)渔伯,所以我們借助于 babel 來進(jìn)行轉(zhuǎn)換顶霞,我們?cè)跒g覽器中引入 babel
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
并將包含jsx
的script
的type
改為type/babel
<script type="text/babel">
const appElement = (
<div className="father">
Fucking React
<div className="child">"用于構(gòu)建用戶界面的 JavaScript 庫"</div>
</div>
);
</script>
默認(rèn)情況下,babel 解析 jsx 時(shí)會(huì)調(diào)用React.createElement
來創(chuàng)建 React 元素
我們可以自定義創(chuàng)建元素的方法锣吼,我們這里的元素就是我們自定義的對(duì)象选浑,見 appElement。通過添加注解即可指定創(chuàng)建元素的方法玄叠,此處指定 createElement
const createElement = (type, props, ...children) => {
console.log(type);
console.log(props);
console.log(children);
};
/** @jsx createElement */
const appElement = (
<div className="father">
Fucking React
<div className="child">"用于構(gòu)建用戶界面的 JavaScript 庫"</div>
</div>
);
現(xiàn)在 babel 進(jìn)行轉(zhuǎn)換的時(shí)候會(huì)調(diào)用我們自定義的 createElement 函數(shù)古徒,該函數(shù)接受的參數(shù)分別為:元素類型type
、元素屬性對(duì)象props
读恃、以及剩余參數(shù)children
即元素的子元素
現(xiàn)在我們要做的是通過這幾個(gè)參數(shù)來創(chuàng)建我們需要的 js 對(duì)象隧膘,然后返回即可
const createElement = (type, props, ...children) => {
return {
type,
props: {
...props,
children,
},
};
};
/** @jsx createElement */
const appElement = (
<div className="father">
Fucking React
<div className="child">用于構(gòu)建用戶界面的 JavaScript 庫</div>
</div>
);
console.log(appElement);
打印一下轉(zhuǎn)換后的 appElement:
{
type: "div",
props: {
className: "father",
children: [
"Fucking React",
{
type: "div",
props: {
className: "child",
children: ["用于構(gòu)建用戶界面的 JavaScript 庫"],
},
},
],
},
};
對(duì)比一下我們需要的結(jié)構(gòu)崎苗,稍微有點(diǎn)問題,如果節(jié)點(diǎn)是字符串舀寓,我們需要轉(zhuǎn)換成這種結(jié)構(gòu):
{
type: "TEXT",
props: {
nodeValue: "Fucking React",
children: [],
},
},
改進(jìn)一下createElement
const createElement = (type, props, ...children) => {
return {
type,
props: {
...props,
children: children.map((child) =>
typeof child === "string"
? {
type: "TEXT",
props: {
nodeValue: child,
children: [],
},
}
: child
),
},
};
};
現(xiàn)在我們可以在代碼中使用 jsx 而不用再寫對(duì)象了胆数,babel 會(huì)幫我們把 jsx 轉(zhuǎn)換成對(duì)應(yīng)的對(duì)象結(jié)構(gòu),然后調(diào)用 render 方法即可渲染到頁面上
5 總結(jié)
至此互墓,我們完成了從命令式編程到聲明式編程的轉(zhuǎn)變必尼,我們已經(jīng)完成了“乞丐版 React”的功能有:
-
createElement
創(chuàng)建元素 -
render
渲染元素到頁面 - 支持
jsx
接下來我們會(huì)從不同方向繼續(xù)完善我們的“洪七公”,敬請(qǐng)期待篡撵!
6 完整代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Build my react</title>
<style>
div {
text-align: center;
}
.father {
display: flex;
flex-direction: column;
justify-content: center;
height: 500px;
background-color: #282c34;
font-size: 30px;
font-weight: 700;
color: #61dafb;
}
.child {
color: #fff;
font-size: 16px;
font-weight: 200;
}
</style>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel" src="./index.js"></script>
</body>
</html>
// index.js
const createElement = (type, props, ...children) => {
return {
type,
props: {
...props,
children: children.map((child) =>
typeof child === "string"
? {
type: "TEXT",
props: {
nodeValue: child,
children: [],
},
}
: child
),
},
};
};
/** @jsx createElement */
const appElement = (
<div className="father">
Fucking React
<div className="child">用于構(gòu)建用戶界面的 JavaScript 庫</div>
</div>
);
const render = (element, container) => {
const dom =
element.type == "TEXT"
? document.createTextNode("")
: document.createElement(element.type);
Object.keys(element.props)
.filter((key) => key !== "children")
.forEach((prop) => (dom[prop] = element.props[prop]));
element.props.children.forEach((child) => render(child, dom));
container.appendChild(dom);
};
render(appElement, document.getElementById("root"));