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

React 元素渲染

核对 React 18 createRoot 挂载流程、元素不可变对象本质、定时更新最小化 DOM 差异对比,以及函数与类组件封装时钟的离线浏览器实测。

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

学完这一章,你能够

React 元素与 React 18 根节点渲染

React 18 引入了来自 `react-dom/client` 的 `ReactDOM.createRoot` 入口,用以启用新的并发渲染架构并替代旧版 `ReactDOM.render`(该旧 API 已在 React 19 移除)。通过 `createRoot(container)` 创建根节点后调用 `root.render(<App />)` 即可把组件树挂载到页面。

React 元素是构成应用的最小描述单元,本质上是轻量级普通 JavaScript 对象,而非沉重的真实浏览器 DOM 节点。元素一旦创建即为不可变对象,不能直接篡改其类型或属性;React DOM 负责依据元素树将真实 DOM 同步到一致状态。本站离线 Chromium 实测冻结元素对象后,`Object.isFrozen(el)` 为 `true`,尝试修改 `el.props.children` 在严格模式下被拦截。

挂载前需在 HTML 中准备一个容器节点(如 `<div id="example"></div>`),由 React DOM 接管其全部子节点,称为“根”DOM 节点。全新单页应用通常只有一个根节点,但在既有传统页面中渐进接入 React 时,也可以为互不干扰的区域分别创建多个独立根节点。实测在同一页面并行挂载 `#example`、`#root-a` 与 `#root-b`,分别稳定输出 `<h1>Hello, world!</h1>`、`Hello, React 18!` 与 `Secondary Root`。

不可变元素的更新机制与最小化 DOM 差异

由于 React 元素不可变,要更新界面需构造新的元素树并再次交给同一 `root.render(element)` 调用(旧资料常写作 `ReactDOM.render`,React 18 应统一复用已创建的 `root` 实例,切勿在 `setInterval` 回调里反复调用 `createRoot`)。以每秒刷新的时钟为例,定时函数每次生成新的 `<div>` 元素树并交由 `root.render` 协调更新。

为提高复用性,可将时钟展示逻辑封装为组件:既可写成接收 `props` 参数的函数组件 `Clock(props)`,也可写成继承 `React.Component` 并在 `render()` 中通过 `this.props` 读取数据的 ES6 类组件(实际业务刷新间隔宜用 `1000` 毫秒而非 `1` 毫秒,后续章节将用组件内部 `state` 替代顶层定时重渲染)。本站实测函数版与类版 `Clock` 在时间推进时均保留原有 `<h1>` 节点并准确更新 `<h2>` 文本。

React DOM 在提交更新前会先对新旧元素树做差异比较(Reconciliation),仅将真正发生变化的最小片段写入真实 DOM。本站通过浏览器 `MutationObserver` 对时钟连续三次刷新(`10:00:01` → `10:00:02` → `10:00:03`)取证:外层 `<div>`、`<h1>` 与 `<h2>` 元素节点引用全程保持同一对象,唯一发生变更的父标签序列仅为 `["H2", "H2"]`,未触发整棵子树重建。

离线 Chromium 验证 createRoot 挂载、元素不可变性与时钟最小化 DOM 差异

python · 阅读源码
"""Offline Chromium lab for React Ch 11: rendering-elements."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>React Rendering Elements Lab</title></head>
<body>
  <div id="example"></div>
  <div id="root-a"></div>
  <div id="root-b"></div>
  <div id="clock-root"></div>
  <div id="fn-root"></div>
  <div id="cls-root"></div>
  <script>
    'use strict';

    // Minimal offline React element + reconciler (preserves unchanged DOM nodes)
    const React = {
      Component: class Component {
        constructor(props) { this.props = props; }
      },
      createElement(type, props, ...children) {
        const flat = children.flat(Infinity).filter(c => c !== null && c !== undefined && c !== false);
        const normalizedProps = Object.assign({}, props || {}, {
          children: flat.length === 1 ? flat[0] : flat
        });
        Object.freeze(normalizedProps);
        return Object.freeze({ $$typeof: 'react.element', type, props: normalizedProps });
      }
    };

    function resolveElement(vnode) {
      if (vnode === null || vnode === undefined || typeof vnode === 'boolean') return null;
      if (typeof vnode === 'string' || typeof vnode === 'number') return String(vnode);
      if (typeof vnode.type === 'function') {
        if (vnode.type.prototype && vnode.type.prototype.render) {
          const inst = new vnode.type(vnode.props);
          return resolveElement(inst.render());
        }
        return resolveElement(vnode.type(vnode.props));
      }
      return vnode;
    }

    function buildDom(vnode) {
      const resolved = resolveElement(vnode);
      if (resolved === null) return document.createTextNode('');
      if (typeof resolved === 'string') return document.createTextNode(resolved);
      const el = document.createElement(resolved.type);
      const kids = Array.isArray(resolved.props.children)
        ? resolved.props.children
        : (resolved.props.children !== undefined ? [resolved.props.children] : []);
      for (const k of kids) el.appendChild(buildDom(k));
      return el;
    }

    function reconcile(parentDom, oldDom, nextVNode) {
      const resolved = resolveElement(nextVNode);
      if (!oldDom) {
        const created = buildDom(resolved);
        parentDom.appendChild(created);
        return created;
      }
      if (typeof resolved === 'string') {
        if (oldDom.nodeType === Node.TEXT_NODE) {
          if (oldDom.nodeValue !== resolved) oldDom.nodeValue = resolved;
          return oldDom;
        }
        const t = document.createTextNode(resolved);
        parentDom.replaceChild(t, oldDom);
        return t;
      }
      if (oldDom.nodeType !== Node.ELEMENT_NODE || oldDom.tagName.toLowerCase() !== resolved.type) {
        const created = buildDom(resolved);
        parentDom.replaceChild(created, oldDom);
        return created;
      }
      const nextKids = Array.isArray(resolved.props.children)
        ? resolved.props.children
        : (resolved.props.children !== undefined ? [resolved.props.children] : []);
      const existing = Array.from(oldDom.childNodes);
      const maxLen = Math.max(existing.length, nextKids.length);
      for (let i = 0; i < maxLen; i++) {
        if (i >= nextKids.length) {
          oldDom.removeChild(existing[i]);
        } else {
          reconcile(oldDom, existing[i] || null, nextKids[i]);
        }
      }
      return oldDom;
    }

    const ReactDOM = {
      createRoot(container) {
        let mounted = null;
        return {
          render(element) {
            mounted = reconcile(container, mounted, element);
          }
        };
      }
    };

    window.runLab = function () {
      // Case 1: createRoot, plain immutable element object, multi-root mount
      const el = React.createElement('h1', null, 'Hello, world!');
      let mutationBlocked = false;
      try { el.props.children = 'Changed'; } catch (e) { mutationBlocked = true; }
      const rootMain = ReactDOM.createRoot(document.getElementById('example'));
      rootMain.render(el);
      const rootA = ReactDOM.createRoot(document.getElementById('root-a'));
      const rootB = ReactDOM.createRoot(document.getElementById('root-b'));
      function App() { return React.createElement('h1', null, 'Hello, React 18!'); }
      rootA.render(React.createElement(App, null));
      rootB.render(React.createElement('span', null, 'Secondary Root'));

      const case1 = {
        is_plain_object: typeof el === 'object' && el.type === 'h1',
        is_frozen: Object.isFrozen(el) && Object.isFrozen(el.props),
        mutation_blocked: mutationBlocked,
        example_html: document.getElementById('example').innerHTML,
        root_a_text: document.getElementById('root-a').textContent,
        root_b_text: document.getElementById('root-b').textContent
      };

      // Case 2: ticking clock minimal DOM diff via MutationObserver
      const clockContainer = document.getElementById('clock-root');
      const clockRoot = ReactDOM.createRoot(clockContainer);
      function tick(timeStr) {
        const tree = React.createElement(
          'div', null,
          React.createElement('h1', null, 'Hello, world!'),
          React.createElement('h2', null, '现在是 ', timeStr, '.')
        );
        clockRoot.render(tree);
      }
      tick('10:00:01');
      const initialDiv = clockContainer.querySelector('div');
      const initialH1 = clockContainer.querySelector('h1');
      const initialH2 = clockContainer.querySelector('h2');
      const mutatedParentTags = [];
      const mo = new MutationObserver(records => {
        for (const r of records) {
          mutatedParentTags.push(r.target.parentElement ? r.target.parentElement.tagName : r.target.tagName);
        }
      });
      mo.observe(clockContainer, { subtree: true, characterData: true, childList: true });
      tick('10:00:02');
      tick('10:00:03');
      const records = mo.takeRecords();
      for (const r of records) {
        mutatedParentTags.push(r.target.parentElement ? r.target.parentElement.tagName : r.target.tagName);
      }
      mo.disconnect();

      const case2 = {
        div_same_node: clockContainer.querySelector('div') === initialDiv,
        h1_same_node: clockContainer.querySelector('h1') === initialH1,
        h2_same_node: clockContainer.querySelector('h2') === initialH2,
        mutated_parent_tags: mutatedParentTags,
        final_h2_text: clockContainer.querySelector('h2').textContent
      };

      // Case 3: Function component Clock(props)
      function FnClock(props) {
        return React.createElement(
          'div', null,
          React.createElement('h1', null, 'Hello, world!'),
          React.createElement('h2', null, '现在是 ', props.timeStr, '.')
        );
      }
      const fnContainer = document.getElementById('fn-root');
      const fnRoot = ReactDOM.createRoot(fnContainer);
      fnRoot.render(React.createElement(FnClock, { timeStr: '14:30:05' }));
      const fnH1Before = fnContainer.querySelector('h1');
      fnRoot.render(React.createElement(FnClock, { timeStr: '14:30:06' }));
      const case3 = {
        h1_preserved: fnContainer.querySelector('h1') === fnH1Before,
        h1_text: fnContainer.querySelector('h1').textContent,
        h2_text: fnContainer.querySelector('h2').textContent
      };

      // Case 4: ES6 Class component Clock extends React.Component using this.props
      class ClassClock extends React.Component {
        render() {
          return React.createElement(
            'div', null,
            React.createElement('h1', null, 'Hello, world!'),
            React.createElement('h2', null, '现在是 ', this.props.timeStr, '.')
          );
        }
      }
      const clsContainer = document.getElementById('cls-root');
      const clsRoot = ReactDOM.createRoot(clsContainer);
      clsRoot.render(React.createElement(ClassClock, { timeStr: '09:00:00' }));
      const clsH1Before = clsContainer.querySelector('h1');
      clsRoot.render(React.createElement(ClassClock, { timeStr: '09:00:01' }));
      const case4 = {
        h1_preserved: clsContainer.querySelector('h1') === clsH1Before,
        h1_text: clsContainer.querySelector('h1').textContent,
        h2_text: clsContainer.querySelector('h2').textContent
      };

      return { case1, case2, case3, case4 };
    };
  </script>
</body>
</html>
"""


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


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)
        out = page.evaluate("window.runLab()")
        browser.close()

    expected = {
        "create_root_and_immutability": {
            "is_plain_object": True,
            "is_frozen": True,
            "mutation_blocked": True,
            "example_html": "<h1>Hello, world!</h1>",
            "root_a_text": "Hello, React 18!",
            "root_b_text": "Secondary Root",
        },
        "clock_minimal_dom_diff": {
            "div_same_node": True,
            "h1_same_node": True,
            "h2_same_node": True,
            "mutated_parent_tags": ["H2", "H2"],
            "final_h2_text": "现在是 10:00:03.",
        },
        "function_clock_component": {
            "h1_preserved": True,
            "h1_text": "Hello, world!",
            "h2_text": "现在是 14:30:06.",
        },
        "class_clock_component": {
            "h1_preserved": True,
            "h1_text": "Hello, world!",
            "h2_text": "现在是 09:00:01.",
        },
    }
    actuals = {
        "create_root_and_immutability": out["case1"],
        "clock_minimal_dom_diff": out["case2"],
        "function_clock_component": out["case3"],
        "class_clock_component": out["case4"],
    }
    cases = [
        {"name": name, "expected": expected[name], "actual": actuals[name], "passed": actuals[name] == expected[name]}
        for name in expected
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对冻结元素不可篡改与多根节点渲染、MutationObserver 仅捕获 H2 文本节点变更且保留 div/h1/h2 引用,以及函数与类版 Clock 更新输出。
离线 Chromium 验证 createRoot 挂载、元素不可变性与时钟最小化 DOM 差异

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

当前源码 SHA256:cf009fd61ed82adcb2c7cd322e75f49fe216dba532df60b2897de41925930def

下载本站示例源码

本地运行

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

下载React 元素渲染实验

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

ZIP SHA256:fdabd2a314a62405fdc627d8ac98c387d71f9801975af419370aebfb282260ae

常见错误与边界

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

练习与解答

为什么在 React 18 定时刷新时钟时应当在定时器外部只调用一次 `ReactDOM.createRoot`,而不是在每次 `tick()` 中重新创建根节点?

展开参考解答

每个 DOM 容器只需建立一个 React 根节点;重复调用 `createRoot` 会触发警告并破坏既有 Fiber 树状态,复用同一 `root.render(...)` 才能让协调器对比前后元素树并仅更新发生变化的文本节点。

规范与官方依据