React從命令式編程到聲明式編程的原理解析
這個系列的目的是通過使用 JS 實現(xiàn)“乞丐版”的 React,讓讀者了解 React 的基本工作原理,體會 React 帶來的構建應用的優(yōu)勢
1 HTML 構建靜態(tài)頁面

使用 HTML 和 CSS,我們很容易可以構建出上圖中的頁面
<!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">用于構建用戶界面的 JavaScript 庫</div>
</div>
</body>
</html>當然這只是一個靜態(tài)的頁面,我們知道,網站中最重要的活動之一是和用戶產生交互,用戶通過觸發(fā)事件來讓網頁產生變化,這時就需要用到 JS
2 DOM 構建頁面
使用 DOM 操作,我們也可以構建上面的靜態(tài)頁面,并且可以動態(tài)地改變頁面、添加事件監(jiān)聽等來讓網頁活動變得更加豐富
我們先改寫一下 HTML 的 body(如果沒有特殊說明,本文不會更改 CSS 的內容),我們將 body 中的內容都去掉,新增一個 id 為 root 都 div 標簽,并且引入index.js。
<div id="root"></div> <script src="./index.js"></script>
index.js內容如下:
const text = document.createTextNode("Fucking React");
const childText = document.createTextNode("用于構建用戶界面的 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 操作,我們也可以構建出同樣的頁面內容,但是缺點很明顯
<div class="father"> Fucking React <div class="child">用于構建用戶界面的 JavaScript 庫</div> </div>
原本只要寥寥幾行 HTML 的頁面。使用 DOM 之后,為了描述元素的嵌套關系、屬性、內容等,代碼量驟增,并且可讀性非常差。這就是命令式編程,我們需要一步一步地指揮計算機去做事
這還只是一個簡單的靜態(tài)頁面,沒有任何交互,試想一下,如果一個非常復雜的網頁都是用 DOM 來構建,不好意思,我不想努力了~
3 從命令式到聲明式
觀察上述 index.js,我們不難發(fā)現(xiàn),在創(chuàng)建每個節(jié)點的時候其實可以抽象出一組重復操作:
- 根據類型創(chuàng)建元素
- 添加元素屬性(如 className)
- 逐一添加子元素
對于元素的嵌套關系和自身屬性,我們可以利用對象來描述
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: "用于構建用戶界面的 JavaScript 庫",
children: [],
},
},
],
},
},
],
},
};其中,type表示元素類型,特殊地,對于字符串文本,我們用TEXT表示;props對象用來描述元素自身的屬性,比如 CSS 類名、children 子元素、nodeValue
我們將頁面中的元素用 JS 對象來描述,天然地形成了一種樹狀結構,接著利用遞歸遍歷對象就可以將重復的 DOM 操作去除,我們構建如下 render 函數來將上述 JS 對象渲染到頁面上:
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 函數:
render(appElement, document.getElementById("root"));現(xiàn)在我們只需要將我們想要的頁面結構通過 JS 對象描述出來,然后調用 render 函數,JS 就會幫我們將頁面渲染出來,而無需一步步地書寫每一步操作
這就是聲明式編程,我們需要做的是描述目標的性質,讓計算機明白目標,而非流程。
對比命令式和聲明式編程,體會兩者的區(qū)別
4 JSX
對比 JS 對象和 HTML,JS 對象的可讀性還是不行,所以 React 引入了 JSX 這種 JavaScript 的語法擴展
我們的 appElement 變成了這樣:
// jsx
const appElement = (
<div className="father">
Fucking React
<div className="child">"用于構建用戶界面的 JavaScript 庫"</div>
</div>
);現(xiàn)在描述元素是不是變得超級爽!
然而這玩意兒 JS 并不認識,所以我們還得把這玩意兒解析成 JS 能認識的語法,解析不是本文的重點,所以我們借助于 babel 來進行轉換,我們在瀏覽器中引入 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">"用于構建用戶界面的 JavaScript 庫"</div>
</div>
);
</script>默認情況下,babel 解析 jsx 時會調用React.createElement來創(chuàng)建 React 元素
我們可以自定義創(chuàng)建元素的方法,我們這里的元素就是我們自定義的對象,見 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">"用于構建用戶界面的 JavaScript 庫"</div>
</div>
);現(xiàn)在 babel 進行轉換的時候會調用我們自定義的 createElement 函數,該函數接受的參數分別為:元素類型type、元素屬性對象props、以及剩余參數children即元素的子元素
現(xiàn)在我們要做的是通過這幾個參數來創(chuàng)建我們需要的 js 對象,然后返回即可
const createElement = (type, props, ...children) => {
return {
type,
props: {
...props,
children,
},
};
};
/** @jsx createElement */
const appElement = (
<div className="father">
Fucking React
<div className="child">用于構建用戶界面的 JavaScript 庫</div>
</div>
);
console.log(appElement);打印一下轉換后的 appElement:
{
type: "div",
props: {
className: "father",
children: [
"Fucking React",
{
type: "div",
props: {
className: "child",
children: ["用于構建用戶界面的 JavaScript 庫"],
},
},
],
},
};對比一下我們需要的結構,稍微有點問題,如果節(jié)點是字符串,我們需要轉換成這種結構:
{
type: "TEXT",
props: {
nodeValue: "Fucking React",
children: [],
},
},改進一下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 而不用再寫對象了,babel 會幫我們把 jsx 轉換成對應的對象結構,然后調用 render 方法即可渲染到頁面上
5 總結
至此,我們完成了從命令式編程到聲明式編程的轉變,我們已經完成了“乞丐版 React”的功能有:
createElement創(chuàng)建元素render渲染元素到頁面支持jsx
接下來我們會從不同方向繼續(xù)完善我們的“洪七公”,敬請期待!
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">用于構建用戶界面的 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"));到此這篇關于React從命令式編程到聲明式編程的文章就介紹到這了,更多相關React聲明式編程內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
React useImperativeHandle處理組件狀態(tài)和生命周期用法詳解
React Hooks 為我們提供了一種全新的方式來處理組件的狀態(tài)和生命周期,useImperativeHandle是一個相對較少被提及的Hook,但在某些場景下,它是非常有用的,本文將深討useImperativeHandle的用法,并通過實例來加深理解2023-09-09
react hooks使用Echarts圖表中遇到的情況及相關配置問題
這篇文章主要介紹了react hooks使用Echarts圖表中遇到的情況及相關配置問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
VSCode 配置React Native開發(fā)環(huán)境的方法
本篇文章主要介紹了VSCode 配置React Native開發(fā)環(huán)境的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12

