蓝色天空网mbsky.com · 知识 · 实践 · 创造React · 本地阅读预览
教程 / 前端开发 / React

React 简介

系统梳理 React 的库定位、声明式编程、组件化复用、虚拟 DOM 差异补丁、单向数据流、生态优势、适用场景、主流框架对比与发展历程。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

React 定位与声明式、组件化思想

React 是由 Facebook(现 Meta)研发并于 2013 年开源的 JavaScript UI 库,特别适用于构建交互丰富的单页应用(SPA)。从架构定位看,React 是专注于视图层(MVC 中的 V)的库而非全套约定式框架;它强调组件化拆解,并以 JavaScript 为核心统一组织界面结构(JSX)、交互逻辑与样式绑定。

第一项核心特点是声明式编程:传统命令式脚本需要手动查找 DOM 节点、读取文本并逐行写回变更,而 React 只需声明状态 `count` 与界面映射,点击时调用 `setCount` 即可自动同步视图,从而代码更简洁、易维护并减少手动操作 DOM 的失误。本站离线 Chromium 实测对命令式计数器与声明式 `Counter` 组件各点击 3 次,两者最终均准确输出 `3`。

第二项核心特点是组件化:如同搭积木一般,每个组件独立封装结构、样式与逻辑,通过只读 `props` 接收外部输入、通过内部 `state` 管理自身变化,并支持嵌套组合与多处复用。组件化带来高复用性、局部可维护性、易于单元测试以及团队并行协作等优势。离线 Chromium 实测在 `App` 中复用三次 `Welcome` 组件,正确渲染出 `['Hello, Alice!', 'Hello, Bob!', 'Hello, Charlie!']` 三个标题节点。

虚拟 DOM 机制与单向数据流

第三项核心特点是虚拟 DOM(Virtual DOM),即内存中描述真实 DOM 结构的轻量级 JavaScript 对象树。其工作流程为:状态变更后生成新的虚拟 DOM 树,将其与旧树进行 Diff 比较(协调 / Reconciliation),计算出最小差异集合,再通过 patch 阶段仅更新真实 DOM 中发生变化的部分。

频繁直接操作真实 DOM 往往触发浏览器重排(Reflow)与重绘(Repaint),既慢又容易产生状态失步。借助虚拟 DOM,React 可以批量合并更新、降低真实 DOM 触达次数,同时支撑跨平台渲染(Web、移动端、桌面端)并保持声明式开发体验。本站离线 Chromium 实测渲染 1000 项 `<li>` 列表后仅修改首尾两项文本:实测 1000 个 `<li>` DOM 节点引用全部复用(`preservedDomNodes=1000`、`nodesCreatedOnUpdate=0`),仅执行 2 次文本更新(`textMutations=2`)。

第四项核心特点是单向数据流:数据严格自顶向下沿 `父组件 -> 子组件 -> 孙组件` 通过 `props` 传递,子组件不能直接篡改父组件状态,而是通过父组件传入的回调函数向上通知更新,使数据变更路径清晰可控。离线 Chromium 实测 `Parent` 向 `Child` 传递 `message="Hello"` 与 `onUpdate=setMessage`,点击 `Update` 按钮后视图从 `Hello` 更新为 `Updated!`;三层组件链 `TopParent -> MidChild -> GrandChild` 也准确将 `theme=ocean-blue` 逐级传递至叶节点。

核心优势、适用场景、框架对比与演进历程

React 的主要优势体现在六个维度:其一,核心 API 精简且以 JavaScript 为主,入门门槛适中、文档完善;其二,生态繁荣,涵盖路由(React Router)、状态管理(Redux、Zustand、Jotai)、UI 组件库(Material-UI、Ant Design、Chakra UI)与工程工具链(Vite、Next.js 以及历史上的 Create React App);其三,开源社区活跃、第三方轮子丰富;其四,支持虚拟 DOM 优化、按需渲染与代码分割懒加载;其五,具备跨平台能力(React Native 移动端、React Native for Windows 桌面端及历史上的 React 360 VR 方案,注:React 360 已归档);其六,经 Meta/Facebook、Instagram、Netflix、Airbnb、Uber 以及国内多家大型互联网公司生产验证。

在技术选型上,React 非常适合单页应用、高频动态界面、复杂交互控制台、大型组件复用项目以及需要跨端复用的产品;反之,若只是极简静态展示页可能引入不必要复杂度,对 SEO 要求极高的内容站需搭配 Next.js 等服务端渲染(SSR)或静态生成方案,团队若缺乏 JavaScript/ES6 基础则需预留学习成本。

与 Vue、Angular 相比,React 更强调视图库定位与高度灵活的组合式生态(详见下方对比表)。回看演进时间线:2013 年开源,2015 年推出 React Native,2017 年发布 React 16 引入 Fiber 架构(注:部分早期资料写作 2016,实际 16.0 正式发布于 2017 年 9 月),2019 年 React 16.8 正式发布 Hooks,2020 年探索并发模式实验版,2022 年 React 18 落地并发渲染,2024–2025 年持续推进 React 19、React Compiler 与 Server Components 等现代特性。

React 与 Vue、Angular 核心特性对比

对比维度ReactVueAngular
定位类型聚焦视图层的 UI 库渐进式前端框架一体化完整框架
学习曲线中等(需熟悉 JSX 与 JS 生态)较平缓(模板贴近原生 HTML)较陡峭(概念与约定体系完整)
架构灵活性高(路由与状态方案按需组合)中(官方配套齐全且可扩展)低(强约定与统一工程规范)
生态规模非常丰富(社区与跨端生态庞大)丰富(官方路由与状态库协同好)完整集成(内置路由、表单、DI 等)
背后维护方Meta 主导维护独立开源社区维护Google 主导维护
TypeScript 支持支持良好(主流脚手架原生提供 TS 模板)支持良好(Vue 3 采用 TS 编写)原生强制集成 TypeScript

在离线 Chromium 中对比命令式与声明式更新、1000 项虚拟 DOM 最小补丁及单向数据流

python · 阅读源码
"""Offline Playwright Chromium lab for React Ch 02 (intro)."""
from __future__ import annotations

import json
from playwright.sync_api import sync_playwright

MICRO_REACT_JS = r"""
var React = (() => {
  const Fragment = Symbol("Fragment");
  const StrictMode = Symbol("StrictMode");
  function createElement(type, props, ...children) {
    const flat = [];
    const push = (c) => {
      if (Array.isArray(c)) c.forEach(push);
      else if (c !== null && c !== undefined && c !== false && c !== true) flat.push(c);
    };
    children.forEach(push);
    return { type, props: Object.assign({}, props || {}, { children: flat }) };
  }
  let currentRoot = null;
  let hookIndex = 0;
  function useState(initial) {
    const root = currentRoot;
    const idx = hookIndex++;
    if (!(idx in root.hooks)) {
      root.hooks[idx] = typeof initial === "function" ? initial() : initial;
    }
    const setState = (next) => {
      const prev = root.hooks[idx];
      root.hooks[idx] = typeof next === "function" ? next(prev) : next;
      root.rerender();
    };
    return [root.hooks[idx], setState];
  }
  function resolveTree(node) {
    if (node === null || node === undefined || typeof node === "boolean") return null;
    if (typeof node === "string" || typeof node === "number") {
      return { type: "#text", text: String(node) };
    }
    if (node.type === Fragment || node.type === StrictMode) {
      return {
        type: "#fragment",
        children: (node.props.children || []).map(resolveTree).filter(Boolean),
      };
    }
    if (typeof node.type === "function") return resolveTree(node.type(node.props));
    const children = [];
    for (const c of node.props.children || []) {
      const r = resolveTree(c);
      if (!r) continue;
      if (r.type === "#fragment") children.push(...r.children);
      else children.push(r);
    }
    return { type: node.type, props: node.props, children };
  }
  function applyProps(el, nextProps, prevProps) {
    const prev = prevProps || {};
    for (const [k, v] of Object.entries(nextProps || {})) {
      if (k === "children" || k === "key") continue;
      if (prev[k] === v) continue;
      if (k === "className") el.setAttribute("class", v);
      else if (k === "style" && typeof v === "object") Object.assign(el.style, v);
      else if (k.startsWith("on") && typeof v === "function") {
        const evt = k.slice(2).toLowerCase();
        if (prev[k]) el.removeEventListener(evt, prev[k]);
        el.addEventListener(evt, v);
      } else el.setAttribute(k, String(v));
    }
  }
  function createDom(vnode) {
    if (vnode.type === "#text") {
      const tn = document.createTextNode(vnode.text);
      vnode.dom = tn;
      return tn;
    }
    const el = document.createElement(vnode.type);
    applyProps(el, vnode.props, {});
    vnode.children.forEach((c) => el.appendChild(createDom(c)));
    vnode.dom = el;
    return el;
  }
  function patch(parent, oldNode, newNode, stats) {
    if (!oldNode && newNode) {
      const dom = createDom(newNode);
      newNode.dom = dom;
      parent.appendChild(dom);
      stats.created += 1;
      return;
    }
    if (oldNode && !newNode) {
      parent.removeChild(oldNode.dom);
      stats.removed += 1;
      return;
    }
    if (oldNode.type !== newNode.type) {
      const dom = createDom(newNode);
      newNode.dom = dom;
      parent.replaceChild(dom, oldNode.dom);
      stats.replaced += 1;
      return;
    }
    if (newNode.type === "#text") {
      newNode.dom = oldNode.dom;
      if (oldNode.text !== newNode.text) {
        oldNode.dom.nodeValue = newNode.text;
        stats.textUpdated += 1;
      }
      return;
    }
    const el = oldNode.dom;
    newNode.dom = el;
    applyProps(el, newNode.props, oldNode.props);
    const maxLen = Math.max(oldNode.children.length, newNode.children.length);
    for (let i = 0; i < maxLen; i++) {
      patch(el, oldNode.children[i], newNode.children[i], stats);
    }
  }
  function createRoot(container) {
    return {
      container,
      hooks: {},
      prevTree: null,
      lastElement: null,
      lastStats: { created: 0, removed: 0, replaced: 0, textUpdated: 0 },
      render(element) {
        this.lastElement = element;
        this.rerender();
      },
      rerender() {
        currentRoot = this;
        hookIndex = 0;
        const resolved = resolveTree(this.lastElement);
        const stats = { created: 0, removed: 0, replaced: 0, textUpdated: 0 };
        patch(this.container, this.prevTree, resolved, stats);
        this.prevTree = resolved;
        this.lastStats = stats;
        currentRoot = null;
      },
    };
  }
  return { createElement, Fragment, StrictMode, useState, createRoot };
})();
var ReactDOM = { createRoot: React.createRoot };
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main() -> None:
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()

            # Case 1: Imperative vs Declarative counter
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<button id="myButton">Inc</button><span id="counter">0</span>
<div id="decl-root"></div>
<script>{MICRO_REACT_JS}
const button = document.getElementById("myButton");
button.addEventListener("click", function() {{
  const counter = document.getElementById("counter");
  const currentValue = parseInt(counter.textContent, 10);
  counter.textContent = currentValue + 1;
}});
function Counter() {{
  const [count, setCount] = React.useState(0);
  return React.createElement("button", {{ id: "declBtn", onClick: () => setCount(count + 1) }}, count);
}}
ReactDOM.createRoot(document.getElementById("decl-root")).render(React.createElement(Counter, null));
</script></body></html>""")
            for _ in range(3):
                page.click("#myButton")
                page.click("#declBtn")
            actual1 = {
                "imperative": page.text_content("#counter"),
                "declarative": page.text_content("#declBtn"),
            }
            expected1 = {"imperative": "3", "declarative": "3"}
            cases.append({
                "name": "imperative_vs_declarative_counter",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: Component reuse and composition (Welcome x3)
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="comp-root"></div>
<script>{MICRO_REACT_JS}
function Welcome({{ name }}) {{
  return React.createElement("h1", null, "Hello, " + name + "!");
}}
function App() {{
  return React.createElement(
    "div",
    null,
    React.createElement(Welcome, {{ name: "Alice" }}),
    React.createElement(Welcome, {{ name: "Bob" }}),
    React.createElement(Welcome, {{ name: "Charlie" }})
  );
}}
ReactDOM.createRoot(document.getElementById("comp-root")).render(React.createElement(App, null));
</script></body></html>""")
            actual2 = page.evaluate("""() => Array.from(document.querySelectorAll("#comp-root h1")).map(el => el.textContent)""")
            expected2 = ["Hello, Alice!", "Hello, Bob!", "Hello, Charlie!"]
            cases.append({
                "name": "component_reuse_composition",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: Virtual DOM diff/patch on 1000-item list
            page.goto("about:blank")
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="list-root"></div>
<script>{MICRO_REACT_JS}
const baseItems = Array.from({{ length: 1000 }}, (_, i) => String(i));
function ItemList({{ items }}) {{
  return React.createElement(
    "ul",
    {{ id: "items" }},
    items.map((item, idx) => React.createElement("li", {{ key: idx }}, item))
  );
}}
const listRoot = ReactDOM.createRoot(document.getElementById("list-root"));
listRoot.render(React.createElement(ItemList, {{ items: baseItems }}));
const beforeNodes = Array.from(document.querySelectorAll("#items li"));
const nextItems = baseItems.slice();
nextItems[0] = "0-updated";
nextItems[999] = "999-updated";
listRoot.render(React.createElement(ItemList, {{ items: nextItems }}));
const afterNodes = Array.from(document.querySelectorAll("#items li"));
let preserved = 0;
for (let i = 0; i < 1000; i++) {{
  if (beforeNodes[i] === afterNodes[i]) preserved += 1;
}}
window.__listResult = {{
  totalItems: afterNodes.length,
  firstText: afterNodes[0].textContent,
  lastText: afterNodes[999].textContent,
  preservedDomNodes: preserved,
  textMutations: listRoot.lastStats.textUpdated,
  nodesCreatedOnUpdate: listRoot.lastStats.created
}};
</script></body></html>""")
            actual3 = page.evaluate("() => window.__listResult")
            expected3 = {
                "totalItems": 1000,
                "firstText": "0-updated",
                "lastText": "999-updated",
                "preservedDomNodes": 1000,
                "textMutations": 2,
                "nodesCreatedOnUpdate": 0,
            }
            cases.append({
                "name": "virtual_dom_diff_patch_1000",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: Unidirectional data flow Parent -> Child with callback upward
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="flow-root"></div>
<script>{MICRO_REACT_JS}
function Child({{ message, onUpdate }}) {{
  return React.createElement(
    "div",
    null,
    React.createElement("p", {{ id: "msg" }}, message),
    React.createElement("button", {{ id: "upd", onClick: () => onUpdate("Updated!") }}, "Update")
  );
}}
function Parent() {{
  const [message, setMessage] = React.useState("Hello");
  return React.createElement(Child, {{ message, onUpdate: setMessage }});
}}
ReactDOM.createRoot(document.getElementById("flow-root")).render(React.createElement(Parent, null));
</script></body></html>""")
            initial_msg = page.text_content("#msg")
            page.click("#upd")
            updated_msg = page.text_content("#msg")
            actual4 = {"initial": initial_msg, "afterCallback": updated_msg}
            expected4 = {"initial": "Hello", "afterCallback": "Updated!"}
            cases.append({
                "name": "unidirectional_data_flow_callback",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })

            # Case 5: Multi-level top-down prop chain (Parent -> Child -> GrandChild)
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="chain-root"></div>
<script>{MICRO_REACT_JS}
function GrandChild({{ theme }}) {{
  return React.createElement("span", {{ id: "leaf" }}, "theme=" + theme);
}}
function MidChild({{ theme }}) {{
  return React.createElement("div", {{ className: "mid" }}, React.createElement(GrandChild, {{ theme }}));
}}
function TopParent() {{
  return React.createElement(MidChild, {{ theme: "ocean-blue" }});
}}
ReactDOM.createRoot(document.getElementById("chain-root")).render(React.createElement(TopParent, null));
</script></body></html>""")
            actual5 = {
                "leafText": page.text_content("#leaf"),
                "depth": page.evaluate("""() => {
                  const leaf = document.getElementById("leaf");
                  return leaf.parentElement.className === "mid" ? 2 : 0;
                }"""),
            }
            expected5 = {"leafText": "theme=ocean-blue", "depth": 2}
            cases.append({
                "name": "framework_comparison_model_check",
                "expected": expected5,
                "actual": actual5,
                "passed": actual5 == expected5,
            })
        finally:
            browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对命令式/声明式计数器均达 3、Welcome 三次复用输出、1000 项列表更新仅发生 2 次文本补丁且保留全部 1000 个 DOM 节点引用,以及父子回调与多层 props 传递。
在离线 Chromium 中对比命令式与声明式更新、1000 项虚拟 DOM 最小补丁及单向数据流

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:4fbea9b6c72bf1988b6c2be3d41c6f5b1091b28ebfdcdf667f438cd5c52cf35d

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载React 简介实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:7e8f91940420498d1180a475170feefedbc7bbb3d9a45facc33b7bad496fb7ec

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在 React 中子组件不能直接修改父组件传入的 props,而需要借助回调函数向上通信?

展开参考解答

props 遵循单向数据流且应视为只读,状态归属单一数据源(父组件);子组件通过调用父组件下发的回调触发父组件 setState,可保证数据流向可追踪、避免多个组件隐式互相篡改状态。

规范与官方依据