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

在离线 Chromium 中验证 CRA 目录模型、类组件、React 18 createRoot 与函数组件拆分

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-install.py
explore-install.py217 行
"""Offline Playwright Chromium lab for React Ch 03 (install / NPM & CRA)."""
from __future__ import annotations

import json
from playwright.sync_api import sync_playwright

MICRO_REACT_JS = r"""
var React = (() => {
  class Component {
    constructor(props) { this.props = props || {}; this.state = {}; }
    render() { return null; }
  }
  Component.prototype.isReactClass = true;
  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 }) };
  }
  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 (typeof node.type === "function") {
      if (node.type.prototype && node.type.prototype.isReactClass) {
        return resolveTree(new node.type(node.props).render());
      }
      return resolveTree(node.type(node.props));
    }
    return {
      type: node.type,
      props: node.props,
      children: (node.props.children || []).map(resolveTree).filter(Boolean),
    };
  }
  function createDom(vnode) {
    if (vnode.type === "#text") return document.createTextNode(vnode.text);
    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 el.setAttribute(k, String(v));
    }
    vnode.children.forEach((c) => el.appendChild(createDom(c)));
    return el;
  }
  function createRoot(container) {
    return {
      render(element) {
        container.innerHTML = "";
        const resolved = resolveTree(element);
        if (resolved) container.appendChild(createDom(resolved));
      },
    };
  }
  return { Component, createElement, 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: CRA project structure & public/index.html #root mount verification
            cra_manifest = {
                "public": ["favicon.ico", "index.html", "logo192.png", "logo512.png", "manifest.json", "robots.txt"],
                "src": ["App.css", "App.js", "App.test.js", "index.css", "index.js", "logo.svg", "reportWebVitals.js", "setupTests.js"],
                "root": [".gitignore", "package.json", "README.md", "package-lock.json"],
            }
            page.set_content("""<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="UTF-8"><title>React App</title></head>
<body><div id="root"></div></body></html>""")
            mount_ok = page.evaluate("""() => {
              const r = document.getElementById("root");
              return Boolean(r && r.tagName === "DIV" && r.children.length === 0);
            }""")
            actual1 = {
                "publicCount": len(cra_manifest["public"]),
                "srcCount": len(cra_manifest["src"]),
                "hasRootDiv": mount_ok,
                "registryMirror": "https://registry.npmmirror.com",
            }
            expected1 = {
                "publicCount": 6,
                "srcCount": 8,
                "hasRootDiv": True,
                "registryMirror": "https://registry.npmmirror.com",
            }
            cases.append({
                "name": "cra_project_skeleton_and_scripts",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: Class component App render (src/App.js)
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
const logoDataUri = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'><circle cx='5' cy='5' r='4'/></svg>";
class App extends React.Component {{
  render() {{
    return React.createElement(
      "div", {{ className: "App" }},
      React.createElement(
        "div", {{ className: "App-header" }},
        React.createElement("img", {{ src: logoDataUri, className: "App-logo", alt: "logo" }}),
        React.createElement("h2", null, "欢迎来到 React 示例")
      ),
      React.createElement(
        "p", {{ className: "App-intro" }},
        "你可以在 ",
        React.createElement("code", null, "src/App.js"),
        " 文件中修改。"
      )
    );
  }}
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
            actual2 = page.evaluate("""() => ({
              heading: document.querySelector(".App-header h2").textContent,
              codeTag: document.querySelector(".App-intro code").textContent,
              logoAlt: document.querySelector("img.App-logo").getAttribute("alt")
            })""")
            expected2 = {
                "heading": "欢迎来到 React 示例",
                "codeTag": "src/App.js",
                "logoAlt": "logo",
            }
            cases.append({
                "name": "class_app_component_render",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: React 18 createRoot entry with Hello props
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function Hello(props) {{
  return React.createElement("h1", null, "Hello " + props.name + "!");
}}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(React.createElement(Hello, {{ name: "World" }}));
</script></body></html>""")
            actual3 = {"text": page.text_content("#root h1")}
            expected3 = {"text": "Hello World!"}
            cases.append({
                "name": "create_root_hello_props",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: Function App component -> composed Hello child component
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="step1"></div><div id="step2"></div>
<script>{MICRO_REACT_JS}
function AppSingle() {{
  return React.createElement(
    "div", {{ className: "App" }},
    React.createElement("header", {{ className: "App-header" }},
      React.createElement("h1", null, "Hello, React!"))
  );
}}
function Hello() {{
  return React.createElement("h1", null, "Hello from a new component!");
}}
function AppComposed() {{
  return React.createElement(
    "div", {{ className: "App" }},
    React.createElement("header", {{ className: "App-header" }},
      React.createElement(Hello, null))
  );
}}
ReactDOM.createRoot(document.getElementById("step1")).render(React.createElement(AppSingle, null));
ReactDOM.createRoot(document.getElementById("step2")).render(React.createElement(AppComposed, null));
</script></body></html>""")
            actual4 = {
                "singleApp": page.text_content("#step1 header.App-header h1"),
                "composedChild": page.text_content("#step2 header.App-header h1"),
            }
            expected4 = {
                "singleApp": "Hello, React!",
                "composedChild": "Hello from a new component!",
            }
            cases.append({
                "name": "modular_hello_in_app",
                "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-install-lab/explore-install.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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