蓝色天空.知识 · 实践 · 创造
我的收藏
React 教程目录 42章
React / LEARN BY DOING

React 安装(NPM)

说明 Node.js/npm 环境检查、国内镜像配置、Create React App 传统脚手架结构与废弃现状,并在离线 Chromium 中实测类组件、React 18 createRoot 入口与函数组件拆分。

学完这一章,你能够

  • 说明 Node.js/npm 环境检查、国内镜像配置、Create React App 传统脚手架结构与废弃现状,并在离线 Chromium 中实测类组件、React 18 createRoot 入口与函数组件拆分。

Node.js 环境与国内镜像配置

使用工程化工具开发 React 前,需要先在本机安装 Node.js 与 npm,并在终端运行 `node -v` 与 `npm -v` 核对版本。早期 React 生态常搭配 CommonJS 模块打包工具(如 Browserify 或 Webpack),现代项目则普遍直接使用原生 ES Modules 配合 Vite 或框架自带构建链路。

如果默认官方源下载较慢,可通过 `npm config set registry https://registry.npmmirror.com` 将 npm 镜像切换至国内 npmmirror 源,或按需安装 `cnpm` 命令行工具再执行 `cnpm install <包名>`。注意:历史域名 `npm.taobao.org` 已全面迁移至 `npmmirror.com`,新环境应直接使用 `https://registry.npmmirror.com`。

Create React App 脚手架与目录结构

Create React App(CRA)曾是 Facebook 推出的零配置 React 脚手架,内部集成 Webpack 与 ES6/JSX 编译能力。历史上可通过 `npx create-react-app my-app`(npm 5.2+ 内置 `npx`,无需全局安装)或全局安装后运行 `create-react-app my-app && cd my-app && npm start` 启动位于 `http://localhost:3000/` 的开发服务器。需要特别提醒:React 官方已正式弃用 Create React App,新项目推荐改用 Vite 或 Next.js 等现代工具链(详见下一章)。

典型 CRA 项目顶层包含 `node_modules/`(npm/yarn 自动安装的第三方依赖目录)与 `public/`(不经 Webpack 打包、直接复制到构建产物的静态目录)。`public/` 下常见文件包括:`favicon.ico`(标签页图标)、`index.html`(含 `<div id="root">` 挂载点的 HTML 模板)、`logo192.png` 与 `logo512.png`(PWA 图标)、`manifest.json`(Web 应用清单元数据)及 `robots.txt`(爬虫抓取规则)。

`src/` 存放核心应用源码:`App.css`、`App.js` 与 `App.test.js` 分别对应主组件样式、逻辑与测试,`index.css` 为全局样式,`index.js` 负责挂载根组件到 DOM,`logo.svg` 为图标素材,`reportWebVitals.js` 与 `setupTests.js` 用于性能上报与测试初始化。根目录还包含 `.gitignore`(Git 忽略清单)、`package.json`(元信息、脚本与依赖)、`README.md`(说明文档)以及 `package-lock.json` 或 `yarn.lock`(精确依赖版本锁定文件)。本站离线脚本核验了上述 6 个 `public/` 文件、8 个 `src/` 文件及 `#root` 挂载点结构。

修改 App 组件、React 18 入口与拆分自定义组件

编辑 `src/App.js` 后,开发服务器会自动刷新页面。早期的类组件写法继承自 `React.Component` 并在 `render()` 中返回 JSX(如包含 `div.App`、`div.App-header`、图标及 `p.App-intro` 中的 `<code>src/App.js</code>` 提示)。本站离线 Chromium 实测渲染该类组件结构,正确产出 `<h2>欢迎来到 React 示例</h2>` 与 `<code>src/App.js</code>`。

查看入口文件 `src/index.js` 时需注意版本演进:React 18 起旧版 `ReactDOM.render` 已被废弃(React 19 已彻底移除),应改为从 `react-dom/client` 导入 `createRoot`(注:部分旧教程误写成 `import ReactDOM from 'react-dom'` 后再调 `createRoot`,实际须从 `react-dom/client` 导入)。离线 Chromium 实测 `ReactDOM.createRoot(document.getElementById("root")).render(<Hello name="World" />)`,在 `#root h1` 中准确输出 `Hello World!`。

现代 React 更推荐简洁的函数组件:先将 `App.js` 改为返回 `<h1>Hello, React!</h1>` 的函数组件,再在 `src/` 下新建 `Hello.js` 导出独立组件 `Hello`,最后在 `App.js` 中 `import Hello from './Hello'` 并渲染 `<Hello />`。离线 Chromium 实测两步演进:单组件阶段输出 `Hello, React!`,拆分组合后 `<header class="App-header">` 内准确渲染子组件文本 `Hello from a new component!`。

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

含完整源码 · 217 行
展开查看收起
python
"""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()
核对 CRA 6 个 public 文件与 8 个 src 文件清单及 #root 挂载点、类组件 App 渲染结果、createRoot 渲染 Hello World!,以及单组件 Hello, React! 与组合子组件 Hello from a new component!。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a3152.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:React

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

下载课程关联工程包:React

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

React 18 引入并发渲染后废弃了 ReactDOM.render(React 19 已移除),新代码必须从 react-dom/client 导入 createRoot(如 import { createRoot } from 'react-dom/client')再调用 createRoot(container).render(...)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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