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

在离线 Chromium 中验证核心模板/CSS/package.json 约定、函数与类组件及 JSX/Props/State

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-project-intro.py
explore-project-intro.py291 行
"""Offline Playwright Chromium lab for React Ch 10 (project-intro)."""
from __future__ import annotations

import json
import re
from playwright.sync_api import sync_playwright

MICRO_REACT_JS = r"""
var React = (() => {
  const StrictMode = Symbol("StrictMode");
  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 }) };
  }
  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") {
      if (node.type.prototype && node.type.prototype.isReactClass) {
        return resolveTree(new node.type(node.props).render());
      }
      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, Component, createElement, useState, createRoot };
})();
var ReactDOM = { createRoot: React.createRoot };
"""

PACKAGE_JSON_EXAMPLE = """{
  "name": "my-react-app",
  "version": "1.0.0",
  "scripts": {
    "start": "react-scripts start", // 启动开发服务器
    "build": "react-scripts build", // 构建生产环境代码
    "test": "react-scripts test",   // 运行测试
    "eject": "react-scripts eject"  // 弹出配置(高级用法)
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1"
  }
}"""


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 = []
    # Strip trailing // comments before JSON parsing (standard package.json forbids comments)
    clean_pkg = re.sub(r"\s*//.*$", "", PACKAGE_JSON_EXAMPLE, flags=re.MULTILINE)
    pkg = json.loads(clean_pkg)

    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()

            # Case 1: Core files (public/index.html + App.css + index.css + package.json)
            page.set_content(f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>React App</title>
<style>
body {{ margin: 0; font-family: Arial, sans-serif; }}
.App {{ text-align: center; margin-top: 50px; }}
</style>
</head>
<body>
<div id="root"></div>
<script>{MICRO_REACT_JS}
function App() {{
  return React.createElement("div", {{ className: "App" }}, React.createElement("h1", null, "Hello, React!"));
}}
ReactDOM.createRoot(document.getElementById("root")).render(
  React.createElement(React.StrictMode, null, React.createElement(App, null))
);
</script>
</body></html>""")
            dom_css = page.evaluate("""() => {
              const app = document.querySelector("#root .App");
              const appCs = getComputedStyle(app);
              const bodyCs = getComputedStyle(document.body);
              return {
                title: document.title,
                heading: app.querySelector("h1").textContent,
                textAlign: appCs.textAlign,
                marginTop: appCs.marginTop,
                bodyMargin: bodyCs.marginTop
              };
            }""")
            actual1 = {
                **dom_css,
                "scripts": sorted(pkg["scripts"].keys()),
                "reactDep": pkg["dependencies"]["react"],
            }
            expected1 = {
                "title": "React App",
                "heading": "Hello, React!",
                "textAlign": "center",
                "marginTop": "50px",
                "bodyMargin": "0px",
                "scripts": ["build", "eject", "start", "test"],
                "reactDep": "^18.2.0",
            }
            cases.append({
                "name": "core_files_html_css_package",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: Function component vs Class component
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="fn-root"></div><div id="cls-root"></div>
<script>{MICRO_REACT_JS}
function FnComponent() {{
  return React.createElement("div", null, React.createElement("h2", null, "这是一个函数定义的组件"));
}}
class ClassComponent extends React.Component {{
  render() {{
    return React.createElement("div", null, React.createElement("h2", null, "这是一个类组件"));
  }}
}}
ReactDOM.createRoot(document.getElementById("fn-root")).render(React.createElement(FnComponent, null));
ReactDOM.createRoot(document.getElementById("cls-root")).render(React.createElement(ClassComponent, null));
</script></body></html>""")
            actual2 = {
                "functionText": page.text_content("#fn-root div h2"),
                "classText": page.text_content("#cls-root div h2"),
            }
            expected2 = {
                "functionText": "这是一个函数定义的组件",
                "classText": "这是一个类组件",
            }
            cases.append({
                "name": "function_vs_class_component",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: JSX element expression
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="jsx-root"></div>
<script>{MICRO_REACT_JS}
const element = React.createElement("h1", null, "Hello, JSX!");
ReactDOM.createRoot(document.getElementById("jsx-root")).render(element);
</script></body></html>""")
            actual3 = page.evaluate("""() => {
              const el = document.querySelector("#jsx-root h1");
              return { tag: el.tagName, text: el.textContent };
            }""")
            expected3 = {"tag": "H1", "text": "Hello, JSX!"}
            cases.append({
                "name": "jsx_expression_element",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: Props parent-to-child
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="props-root"></div>
<script>{MICRO_REACT_JS}
function Welcome(props) {{
  return React.createElement("h1", null, "Hello, " + props.name);
}}
function App() {{
  return React.createElement(Welcome, {{ name: "React" }});
}}
ReactDOM.createRoot(document.getElementById("props-root")).render(React.createElement(App, null));
</script></body></html>""")
            actual4 = {"text": page.text_content("#props-root h1")}
            expected4 = {"text": "Hello, React"}
            cases.append({
                "name": "props_parent_to_child",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })

            # Case 5: State Counter hook
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="state-root"></div>
<script>{MICRO_REACT_JS}
function Counter() {{
  const [count, setCount] = React.useState(0);
  return React.createElement(
    "div", null,
    React.createElement("p", {{ id: "cnt" }}, "Count: " + count),
    React.createElement("button", {{ id: "inc", onClick: () => setCount(count + 1) }}, "Increment")
  );
}}
ReactDOM.createRoot(document.getElementById("state-root")).render(React.createElement(Counter, null));
</script></body></html>""")
            before = page.text_content("#cnt")
            page.click("#inc")
            page.click("#inc")
            after = page.text_content("#cnt")
            actual5 = {"before": before, "after": after}
            expected5 = {"before": "Count: 0", "after": "Count: 2"}
            cases.append({
                "name": "state_counter_hook",
                "expected": expected5,
                "actual": actual5,
                "passed": actual5 == expected5,
            })
        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-project-intro-lab/explore-project-intro.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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