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

React AI 开发

客观介绍使用桌面 AI 智能体(如 DuMate)以自然语言驱动生成 React 项目的工作流、系统要求、本地依赖安装与运行验证要点,并在离线 Chromium 中实测标准 React 二维码应用状态逻辑。

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

学完这一章,你能够

AI 智能体辅助开发 React 的定位与环境前提

除手动搭建脚手架外,开发者也可借助桌面级 AI 办公/编程智能体(例如百度推出的 DuMate 桌面客户端)通过自然语言提示(常称 Vibe Coding)快速生成 React 应用原型。与仅输出代码片段的普通对话窗口不同,智能体可自动拆解需求、创建完整工程目录并打包源码。按工具官方说明,该桌面客户端面向 macOS(Apple Silicon M 系列芯片)与 Windows(x86 架构)系统运行。

常规接入流程为下载对应平台安装包、按向导完成本地安装并使用手机号或平台账号登录客户端。进入主界面后,客户端区分用于日常问答的普通/通用模式与面向工程搭建的开发模式,开发模式内通常预置常见应用模板供参考。

自然语言生成、下载源码与本地 Vite 启动验证

在开发模式输入框提交需求(例如“使用 React 框架生成一个在线二维码工具”),待智能体完成多步规划、代码生成与打包后,可下载获得标准前端项目压缩包(压缩包一般不含 `node_modules/` 与 `dist/`)。随后在本地终端进入解压目录(如 `cd qr-code-studio`)执行 `npm install` 安装依赖并审阅 `index.html`、`package.json` 与 `src/` 源码,再运行 `npm run dev` 在默认地址 `http://127.0.0.1:5173/` 启动预览。本站离线 Chromium 实测了一个自研等价 React 二维码工坊组件:初始渲染 `320px · M · https://example.com` 并绘制 SVG 矩阵,交互切换网址为 `https://react.dev` 且将容错级别改为 `H` 后,界面摘要同步更新且矩阵哈希发生确定性变化。

注:第三方商业客户端的会员试用、积分活动及设置页邀请码兑换规则均受对应服务商实时政策约束(原参考页面中的活动文案与复制邀请码脚本仅作为内部证据登记、未执行且不在本站公开推广)。工程学习重点应放在审阅 AI 生成的 React 组件结构、验证依赖安全性与本地构建运行质量;本站也以独立 React 按钮组件离线实测了“复制 -> 已复制”状态反馈模式。

在离线 Chromium 中验证 AI 生成风格的 Vite + React 二维码应用架构与状态交互

python · 阅读源码
"""Offline Playwright Chromium lab for React Ch 06 (dumate-dev-react)."""
from __future__ import annotations

import json
from playwright.sync_api import sync_playwright

MICRO_REACT_JS = r"""
var React = (() => {
  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 (typeof node.type === "function") 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 svgTags = new Set(["svg", "rect"]);
    const el = svgTags.has(vnode.type)
      ? document.createElementNS("http://www.w3.org/2000/svg", vnode.type)
      : 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 === "value" && (el.tagName === "TEXTAREA" || el.tagName === "INPUT")) el.value = 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 { createElement, useState, 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: Validate standard AI-generated Vite + React project entry structure (qr-code-studio)
            page.set_content("""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8" /><title>二维码工坊 · 在线二维码生成工具</title></head>
<body><div id="root"></div><script type="module" data-src="/src/main.jsx"></script></body>
</html>""")
            actual1 = page.evaluate("""() => ({
              title: document.title,
              hasRoot: Boolean(document.getElementById("root")),
              entry: document.querySelector("script[type='module']").getAttribute("data-src"),
              devUrl: "http://127.0.0.1:5173/"
            })""")
            expected1 = {
                "title": "二维码工坊 · 在线二维码生成工具",
                "hasRoot": True,
                "entry": "/src/main.jsx",
                "devUrl": "http://127.0.0.1:5173/",
            }
            cases.append({
                "name": "ai_generated_vite_qr_skeleton",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2 & 3: Offline React QR tool UI render + interactive state reconciliation
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function computeBits(text, level) {{
  let hash = 2166136261;
  const src = text + "|" + level;
  for (let i = 0; i < src.length; i++) {{
    hash ^= src.charCodeAt(i);
    hash = Math.imul(hash, 16777619) >>> 0;
  }}
  const cells = [];
  for (let r = 0; r < 7; r++) {{
    for (let c = 0; c < 7; c++) {{
      const bit = ((hash >>> ((r * 7 + c) % 29)) ^ (r + c)) & 1;
      if (bit) cells.push([r, c]);
    }}
  }}
  return {{ hash: hash.toString(16), cells }};
}}
function QrStudio() {{
  const [content, setContent] = React.useState("https://example.com");
  const [level, setLevel] = React.useState("M");
  const [size] = React.useState(320);
  const grid = computeBits(content, level);
  return React.createElement(
    "main", null,
    React.createElement("h1", null, "二维码工坊"),
    React.createElement("textarea", {{ id: "qr-input", value: content }}),
    React.createElement("button", {{ id: "set-text", onClick: () => setContent("https://react.dev") }}, "切换网址"),
    React.createElement("button", {{ id: "set-level-h", onClick: () => setLevel("H") }}, "容错 H"),
    React.createElement("p", {{ id: "summary" }}, size + "px · " + level + " · " + content),
    React.createElement(
      "svg", {{ id: "qr-svg", width: size, height: size, "data-hash": grid.hash }},
      grid.cells.map(([r, c]) => React.createElement("rect", {{ x: c * 10, y: r * 10, width: 10, height: 10 }}))
    )
  );
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(QrStudio, null));
</script></body></html>""")
            initial_qr = page.evaluate("""() => ({
              title: document.querySelector("h1").textContent,
              summary: document.getElementById("summary").textContent,
              rectCount: document.querySelectorAll("#qr-svg rect").length,
              hash: document.getElementById("qr-svg").getAttribute("data-hash")
            })""")
            expected2 = {
                "title": "二维码工坊",
                "summary": "320px · M · https://example.com",
                "hasRects": True,
            }
            actual2 = {
                "title": initial_qr["title"],
                "summary": initial_qr["summary"],
                "hasRects": initial_qr["rectCount"] > 0,
            }
            cases.append({
                "name": "react_qr_tool_ui_render",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            page.click("#set-text")
            page.click("#set-level-h")
            updated_qr = page.evaluate("""() => ({
              summary: document.getElementById("summary").textContent,
              hash: document.getElementById("qr-svg").getAttribute("data-hash")
            })""")
            actual3 = {
                "summary": updated_qr["summary"],
                "hashChanged": updated_qr["hash"] != initial_qr["hash"],
            }
            expected3 = {
                "summary": "320px · H · https://react.dev",
                "hashChanged": True,
            }
            cases.append({
                "name": "react_qr_state_reconciliation",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: Clean self-authored React copy feedback state (not executing any source script)
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="cp"></div>
<script>{MICRO_REACT_JS}
function CopyButton({{ text }}) {{
  const [copied, setCopied] = React.useState(false);
  return React.createElement(
    "button",
    {{ id: "cp-btn", "data-payload": text, onClick: () => setCopied(true) }},
    copied ? "已复制" : "复制"
  );
}}
ReactDOM.createRoot(document.getElementById("cp")).render(
  React.createElement(CopyButton, {{ text: "npm run dev" }})
);
</script></body></html>""")
            before_cp = page.text_content("#cp-btn")
            page.click("#cp-btn")
            after_cp = page.text_content("#cp-btn")
            actual4 = {"before": before_cp, "after": after_cp}
            expected4 = {"before": "复制", "after": "已复制"}
            cases.append({
                "name": "clipboard_copy_pattern_isolated",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })
        finally:
            browser.close()

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 Vite index.html 挂载点约定、自研 React 二维码组件初始渲染与交互状态重算(容错 M -> H 及哈希更新),以及隔离复制按钮状态切换。
在离线 Chromium 中验证 AI 生成风格的 Vite + React 二维码应用架构与状态交互

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

当前源码 SHA256:cde31fef69db857fbf23a82490a81366a30ab941cc34b237241562e7aa8b8a16

下载本站示例源码

本地运行

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

下载React AI 开发实验

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

ZIP SHA256:5769c3a39f1970bb04cc8a675226b11a5968cc5b3364623e39e1f0594ff9681a

常见错误与边界

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

练习与解答

下载 AI 工具生成的 React 项目压缩包后,首次在本地运行前通常需要执行哪两步命令?为什么?

展开参考解答

通常先在项目根目录执行 npm install 安装 package.json 中声明的依赖(压缩包一般不包含体积庞大的 node_modules),再执行 npm run dev 启动 Vite 本地开发服务器进行功能与代码核验。

规范与官方依据