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

React 项目说明

系统拆解典型 React 项目目录与六大核心文件(index.html、index.js、App.js、App.css、index.css、package.json),对比函数组件与类组件,并在离线 Chromium 中实测 JSX、Props、State 与样式规则。

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

学完这一章,你能够

项目整体结构与六大核心文件解析

一个标准 React 工程由多个职责明确的目录与文件协作而成:核心运转依赖 `index.html`、`index.js`(Vite 中为 `main.jsx`)和 `App.js`,界面由函数组件或类组件构成,使用 JSX 描述结构,并以 Props 与 State 分别承担外部输入与内部状态管理。项目顶层通常包含 `node_modules/`、`public/`、`src/`、`package.json`、`package-lock.json` 与 `README.md`。

`public/index.html` 是应用的 HTML 模板,配置字符集、视口元信息与 `<div id="root"></div>` 挂载节点;`src/index.js` 作为入口脚本将根组件 `<App />` 挂载至 `div#root`(传统 CRA 示例写作 `ReactDOM.render`,React 18+ 实际应使用 `react-dom/client` 的 `createRoot`);`src/App.js` 则是根组件,负责组织应用主结构与核心逻辑。

样式与配置方面:`src/App.css` 定义 `.App { text-align: center; margin-top: 50px; }` 等组件样式;`src/index.css` 负责 `body { margin: 0; font-family: Arial, sans-serif; }` 等全局重置;`package.json` 记录项目元数据、`scripts`(如 CRA 时代的 `start`/`build`/`test`/`eject`,以及 Vite 时代的 `dev`/`build`/`preview`)与 `dependencies`(如 `react`、`react-dom`)。注意:标准 JSON 格式不允许 `//` 行内注释,实际 `package.json` 文件中不可直接写入注释。本站离线 Chromium 实测验证了模板标题 `React App`、`.App` 计算样式(`textAlign=center`、`marginTop=50px`)、`body` 外边距 `0px` 以及去注释后的 `package.json` 脚本与 `react: ^18.2.0` 依赖字段。

函数组件、类组件与 JSX / Props / State 核心概念

组件是 React 应用的基本构建块,首先是现代首选的函数组件:在模块中导入 React(启用现代自动 JSX 运行时后可省略显式 `import React`),编写返回 JSX 的普通函数 `function MyComponent()`,再通过 `export default MyComponent` 默认导出供其他文件 `import MyComponent from './MyComponent'` 复用。

其次是历史常见的类组件(现已不推荐在新代码中新增,仅用于理解与维护存量项目):从 `react` 导入 `Component` 基类并定义 `class MyComponent extends Component`,必须实现 `render()` 方法返回描述界面的 JSX(如 `<div><h2>这是一个类组件</h2></div>`),最后同样使用 `export default MyComponent` 导出。本站离线 Chromium 实测同时渲染函数组件与类组件,准确分别输出 `这是一个函数定义的组件` 与 `这是一个类组件`。

支撑组件交互的三大语言与数据要素分别为:JSX(如 `const element = <h1>Hello, JSX!</h1>`,编译期转为 `React.createElement` 调用)、Props(父组件 `App` 向子组件 `Welcome` 传入 `name="React"` 并在子组件以 `{props.name}` 读取),以及 State(使用 `useState(0)` 声明内部计数并在点击 `Increment` 时递增)。本站离线 Chromium 实测逐一验证:JSX 节点输出 `<h1>Hello, JSX!</h1>`,Props 传参输出 `Hello, React`,`Counter` 按钮点击两次后文本从 `Count: 0` 更新为 `Count: 2`。

React 项目日常运行流程

一个完整 React 工程的日常研发通常围绕三条命令展开:开发阶段执行 `npm start` 或 `yarn start`(Vite 项目为 `npm run dev`)在本地端口(CRA 默认 `http://localhost:3000`,Vite 默认 `5173`)实时预览;发布前执行 `npm run build` 或 `yarn build` 生成压缩优化后的静态构建产物;质量保障阶段执行 `npm test` 或 `yarn test` 运行单元测试套件。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对 index.html/App.css/index.css 计算样式与 package.json 字段、函数组件与类组件双渲染输出、Hello, JSX!、Hello, React 及 Counter 计数 0 -> 2。
在离线 Chromium 中验证核心模板/CSS/package.json 约定、函数与类组件及 JSX/Props/State

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

当前源码 SHA256:d2ca0d0eedb88b9a5be36b598fbb62e51aae883c9714c61382b01db4ba4e74e8

下载本站示例源码

本地运行

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

下载React 项目说明实验

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

ZIP SHA256:4e4727684047c49453c2d917db5e0569d0687aecbda4c1855ccd427fc1ee5cc0

常见错误与边界

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

练习与解答

在维护包含 `package.json` 的 React 项目时,为什么不能把教程注释(`// ...`)直接复制到 `package.json` 文件中?函数组件与类组件在定义结构上有何核心区别?

展开参考解答

标准 JSON 语法不支持 `//` 注释,写入 `package.json` 会导致 npm/Vite/Node 解析报错;函数组件直接以函数返回 JSX 并配合 Hooks 管理状态,而类组件必须继承 `React.Component` 并实现 `render()` 方法返回 JSX,新项目推荐统一使用函数组件。

规范与官方依据