蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在离线 Chromium 中验证入口挂载等价性、修改 App、UserProfile 组合与 useState 点击计数

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-creact-first-app.py
explore-creact-first-app.py237 行
"""Offline Playwright Chromium lab for React Ch 09 (creact-first-app)."""
from __future__ import annotations

import json
from playwright.sync_api import sync_playwright

MICRO_REACT_JS = r"""
var React = (() => {
  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) => {
      root.hooks[idx] = typeof next === "function" ? next(root.hooks[idx]) : 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 === 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 createDom(vnode) {
    if (vnode.type === "#text") return document.createTextNode(vnode.text);
    if (vnode.type === "#fragment") {
      const frag = document.createDocumentFragment();
      vnode.children.forEach((c) => frag.appendChild(createDom(c)));
      return frag;
    }
    const el = document.createElement(vnode.type);
    for (const [k, v] of Object.entries(vnode.props || {})) {
      if (k === "children" || k === "key") continue;
      if (k === "className") el.setAttribute("class", v);
      else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2).toLowerCase(), v);
      else el.setAttribute(k, String(v));
    }
    vnode.children.forEach((c) => el.appendChild(createDom(c)));
    return el;
  }
  function createRoot(container) {
    return {
      container,
      hooks: {},
      lastElement: null,
      render(element) { this.lastElement = element; this.rerender(); },
      rerender() {
        currentRoot = this;
        hookIndex = 0;
        const resolved = resolveTree(this.lastElement);
        this.container.innerHTML = "";
        if (resolved) this.container.appendChild(createDom(resolved));
        currentRoot = null;
      },
    };
  }
  return { StrictMode, createElement, useState, createRoot };
})();
var ReactDOM = {
  createRoot: React.createRoot,
  render(element, container) { React.createRoot(container).render(element); }
};
"""


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: React 18 createRoot vs legacy ReactDOM.render output equivalence
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="r18"></div><div id="r17"></div>
<script>{MICRO_REACT_JS}
function App() {{
  return React.createElement("div", {{ className: "App" }}, React.createElement("h1", null, "Hello, React!"));
}}
ReactDOM.createRoot(document.getElementById("r18")).render(
  React.createElement(React.StrictMode, null, React.createElement(App, null))
);
ReactDOM.render(
  React.createElement(React.StrictMode, null, React.createElement(App, null)),
  document.getElementById("r17")
);
</script></body></html>""")
            actual1 = {
                "createRootHtml": page.inner_html("#r18"),
                "legacyRenderHtml": page.inner_html("#r17"),
                "identicalDom": page.inner_html("#r18") == page.inner_html("#r17"),
            }
            expected1 = {
                "createRootHtml": '<div class="App"><h1>Hello, React!</h1></div>',
                "legacyRenderHtml": '<div class="App"><h1>Hello, React!</h1></div>',
                "identicalDom": True,
            }
            cases.append({
                "name": "vite_vs_cra_entry_equivalence",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: Modified App.js with heading and paragraph
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function App() {{
  return React.createElement(
    "div", {{ className: "App" }},
    React.createElement("h1", null, "我的第一个 React App!"),
    React.createElement("p", null, "这是一个段落。")
  );
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
            actual2 = {
                "h1": page.text_content("#root h1"),
                "p": page.text_content("#root p"),
            }
            expected2 = {
                "h1": "我的第一个 React App!",
                "p": "这是一个段落。",
            }
            cases.append({
                "name": "modified_app_heading_paragraph",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: UserProfile JSX composition inside App
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function UserProfile() {{
  const user = {{ name: "Alice", age: 25, location: "中国" }};
  return React.createElement(
    "div", {{ className: "profile" }},
    React.createElement("h2", null, user.name),
    React.createElement("p", null, "Age: " + user.age),
    React.createElement("p", null, "Location: " + user.location)
  );
}}
function App() {{
  return React.createElement(
    "div", {{ className: "App" }},
    React.createElement("h1", null, "我的第一个 React App!"),
    React.createElement(UserProfile, null)
  );
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
            actual3 = page.evaluate("""() => ({
              h1: document.querySelector(".App h1").textContent,
              name: document.querySelector(".profile h2").textContent,
              details: Array.from(document.querySelectorAll(".profile p")).map(p => p.textContent)
            })""")
            expected3 = {
                "h1": "我的第一个 React App!",
                "name": "Alice",
                "details": ["Age: 25", "Location: 中国"],
            }
            cases.append({
                "name": "user_profile_jsx_composition",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: useState + handleClick counter
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function App() {{
  const [count, setCount] = React.useState(0);
  const handleClick = () => {{ setCount(count + 1); }};
  return React.createElement(
    "div", {{ className: "App" }},
    React.createElement("h1", {{ id: "cnt" }}, "Click count: " + count),
    React.createElement("button", {{ id: "inc", onClick: handleClick }}, "Increase")
  );
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
            before = page.text_content("#cnt")
            for _ in range(3):
                page.click("#inc")
            after = page.text_content("#cnt")
            actual4 = {"before": before, "after3Clicks": after}
            expected4 = {"before": "Click count: 0", "after3Clicks": "Click count: 3"}
            cases.append({
                "name": "usestate_click_counter_handler",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })
        finally:
            browser.close()

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


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/react-creact-first-app-lab/explore-creact-first-app.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-creact-first-app.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:React

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3168.zip

下载课程关联工程包:React

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习