從零打造「乞丐版」 React(一)——從命令式編程到聲明式編程

這個系列的目的是通過使用 JS 實現「乞丐版」的 React,讓讀者了解 React 的基本工作原理,體會 React 帶來的構建應用的優勢

1 HTML 構建靜態頁面

截屏2022-09-03 13.29.38

使用 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>

當然這只是一個靜態的頁面,我們知道,網站中最重要的活動之一是和用戶產生交互,用戶通過觸發事件來讓網頁產生變化,這時就需要用到 JS

2 DOM 構建頁面

使用 DOM 操作,我們也可以構建上面的靜態頁面,並且可以動態地改變頁面、添加事件監聽等來讓網頁活動變得更加豐富

我們先改寫一下 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 之後,為了描述元素的嵌套關係、屬性、內容等,代碼量驟增,並且可讀性非常差。這就是命令式編程,我們需要一步一步地指揮計算機去做事

這還只是一個簡單的靜態頁面,沒有任何交互,試想一下,如果一個非常複雜的網頁都是用 DOM 來構建,不好意思,我不想努力了~

3 從命令式到聲明式

觀察上述 index.js,我們不難發現,在創建每個節點的時候其實可以抽象出一組重複操作:

  1. 根據類型創建元素
  2. 添加元素屬性(如 className)
  3. 逐一添加子元素

對於元素的嵌套關係和自身屬性,我們可以利用對象來描述

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"));

現在我們只需要將我們想要的頁面結構通過 JS 對象描述出來,然後調用 render 函數,JS 就會幫我們將頁面渲染出來,而無需一步步地書寫每一步操作

這就是聲明式編程,我們需要做的是描述目標的性質,讓計算機明白目標,而非流程。

對比命令式和聲明式編程,體會兩者的區別

4 JSX

對比 JS 對象和 HTML,JS 對象的可讀性還是不行,所以 React 引入了 JSX 這種 JavaScript 的語法擴展

我們的 appElement 變成了這樣:

// jsx
const appElement = (
  <div className="father">
    Fucking React
    <div className="child">"用於構建用戶界面的 JavaScript 庫"</div>
  </div>
);

現在描述元素是不是變得超級爽!

然而這玩意兒 JS 並不認識,所以我們還得把這玩意兒解析成 JS 能認識的語法,解析不是本文的重點,所以我們藉助於 babel 來進行轉換,我們在瀏覽器中引入 babel

<script src="//unpkg.com/@babel/standalone/babel.min.js"></script>

並將包含jsxscripttype改為type/babel

<script type="text/babel">
const appElement = (
  <div className="father">
    Fucking React
    <div className="child">"用於構建用戶界面的 JavaScript 庫"</div>
  </div>
);
</script>

默認情況下,babel 解析 jsx 時會調用React.createElement來創建 React 元素

我們可以自定義創建元素的方法,我們這裡的元素就是我們自定義的對象,見 appElement。通過添加註解即可指定創建元素的方法,此處指定 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>
);

現在 babel 進行轉換的時候會調用我們自定義的 createElement 函數,該函數接受的參數分別為:元素類型type、元素屬性對象props、以及剩餘參數children即元素的子元素

現在我們要做的是通過這幾個參數來創建我們需要的 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 庫"],
        },
      },
    ],
  },
};

對比一下我們需要的結構,稍微有點問題,如果節點是字符串,我們需要轉換成這種結構:

{
  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
      ),
    },
  };
};

現在我們可以在代碼中使用 jsx 而不用再寫對象了,babel 會幫我們把 jsx 轉換成對應的對象結構,然後調用 render 方法即可渲染到頁面上

5 總結

至此,我們完成了從命令式編程到聲明式編程的轉變,我們已經完成了「乞丐版 React」的功能有:

  1. createElement創建元素
  2. render渲染元素到頁面
  3. 支持jsx

接下來我們會從不同方向繼續完善我們的「洪七公」,敬請期待!

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="//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"));