最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

React從命令式編程到聲明式編程的原理解析

 更新時間:2022年09月19日 14:48:01   作者:Cikayo  
這篇文章主要介紹了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)的頁面,我們知道,網(wǎng)站中最重要的活動之一是和用戶產(chǎn)生交互,用戶通過觸發(fā)事件來讓網(wǎng)頁產(chǎn)生變化,這時就需要用到 JS

2 DOM 構建頁面

使用 DOM 操作,我們也可以構建上面的靜態(tài)頁面,并且可以動態(tài)地改變頁面、添加事件監(jiān)聽等來讓網(wǎng)頁活動變得更加豐富

我們先改寫一下 HTML 的 body(如果沒有特殊說明,本文不會更改 CSS 的內(nèi)容),我們將 body 中的內(nèi)容都去掉,新增一個 id 為 root 都 div 標簽,并且引入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("用于構建用戶界面的 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 操作,我們也可以構建出同樣的頁面內(nèi)容,但是缺點很明顯

<div class="father">
   Fucking React
   <div class="child">用于構建用戶界面的 JavaScript 庫</div>
</div>

原本只要寥寥幾行 HTML 的頁面。使用 DOM 之后,為了描述元素的嵌套關系、屬性、內(nèi)容等,代碼量驟增,并且可讀性非常差。這就是命令式編程,我們需要一步一步地指揮計算機去做事

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

3 從命令式到聲明式

觀察上述 index.js,我們不難發(fā)現(xiàn),在創(chuàng)建每個節(jié)點的時候其實可以抽象出一組重復操作:

  • 根據(jù)類型創(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 函數(shù)來將上述 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);
};

調(diào)用 render 函數(shù):

render(appElement, document.getElementById("root"));

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

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

對比命令式和聲明式編程,體會兩者的區(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 來進行轉(zhuǎn)換,我們在瀏覽器中引入 babel

<script src="https://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 時會調(diào)用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 進行轉(zhuǎn)換的時候會調(diào)用我們自定義的 createElement 函數(shù),該函數(shù)接受的參數(shù)分別為:元素類型type、元素屬性對象props、以及剩余參數(shù)children即元素的子元素

現(xiàn)在我們要做的是通過這幾個參數(shù)來創(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);

打印一下轉(zhuǎn)換后的 appElement:

{
  type: "div",
  props: {
    className: "father",
    children: [
      "Fucking React",
      {
        type: "div",
        props: {
          className: "child",
          children: ["用于構建用戶界面的 JavaScript 庫"],
        },
      },
    ],
  },
};

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

{
  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 轉(zhuǎn)換成對應的對象結構,然后調(diào)用 render 方法即可渲染到頁面上

5 總結

至此,我們完成了從命令式編程到聲明式編程的轉(zhuǎn)變,我們已經(jīng)完成了“乞丐版 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聲明式編程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

纳雍县| 永德县| 焉耆| 慈溪市| 郁南县| 威海市| 岚皋县| 富阳市| 金川县| 柯坪县| 郎溪县| 武穴市| 原阳县| 凤翔县| 华宁县| 平罗县| 太谷县| 湖口县| 应城市| 迁安市| 新宾| 长武县| 崇义县| 灌南县| 阳曲县| 遵义市| 郎溪县| 宝坻区| 临武县| 友谊县| 新平| 南充市| 常熟市| 嵩明县| 淮南市| 萨迦县| 南召县| 琼结县| 靖西县| 台湾省| 安达市|