React 在线生成
概述云端在线 AI 编程平台生成、预览、浏览源码并下载 React 项目的标准流程,并在离线 Chromium 中实测多模式二维码编码工具与 Controls/Preview 组件协同架构。
学完这一章,你能够
- 概述云端在线 AI 编程平台生成、预览、浏览源码并下载 React 项目的标准流程,并在离线 Chromium 中实测多模式二维码编码工具与 Controls/Preview 组件协同架构。
云端在线 AI 生成 React 项目的标准流程
除本地安装 Node.js 与桌面客户端外,许多云端在线 AI 开发平台(如内置云沙箱的在线 Vibe Coding 工具)支持直接在浏览器中注册登录后创建 React 项目,适合快速学习与验证想法。典型步骤为:在任务框输入明确需求(如“使用 React 框架生成一个在线二维码工具”),按需勾选前端设计技能或指定 React 样式风格,随后在任务参数弹窗中选择默认模型并启动云端执行。
平台会在云端工作区自动初始化 `package.json`、`vite.config.js`、`index.html` 与 `src/` 模块并启动开发预览端口(常见为 `5173`);任务完成后点击“访问”即可打开在线预览页体验成品。通过右上角“文件”面板可检视完整目录结构(例如将应用拆分为 `src/App.jsx`、`src/components/Controls.jsx`、`src/components/Preview.jsx` 与 `src/utils/payload.js`)、点击任意文件阅读源代码,并通过菜单将整个项目打包下载到本地继续二次开发。
生成项目的 React 模块化拆分与离线实测
为了把云端生成的工程转化为可理解、可维护的前端代码,学习者应重点核查三层拆分:一是纯函数数据编码工具(如 `src/utils/payload.js` 处理文本、自动补全 `https://` 的网址、WiFi 配置串及 `mailto:` 邮件链接);二是控制面板子组件 `Controls` 通过回调函数上抛用户切换的模式与样式参数;三是展示子组件 `Preview` 依据 `payload` 与 `style` 实时渲染。本站离线 Chromium 实测上述模块化架构:验证了 4 种载荷格式化输出(含 `example.com` 自动补全为 `https://example.com` 与 WiFi 串 `WIFI:T:WPA;S:LabNet;P:pass123;;`),并在界面中点击切换至 `WiFi` 模式与 `Q · 25%` 容错后,预览元数据准确由 `280 × 280 px · 容错 M · 边距 2` 同步为 `280 × 280 px · 容错 Q · 边距 2`。
在离线 Chromium 中验证在线生成风格的 React 多模块目录、Payload 编码与组件状态联动
展开查看收起
"""Offline Playwright Chromium lab for React Ch 08 (online)."""
from __future__ import annotations
import json
from playwright.sync_api import sync_playwright
MICRO_REACT_JS = r"""
const 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 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 { createElement, useState, createRoot };
})();
const 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: Online-generated Vite 5 + React 18 multi-module skeleton verification
project_files = [
"index.html",
"package.json",
"vite.config.js",
"src/main.jsx",
"src/App.jsx",
"src/index.css",
"src/components/Controls.jsx",
"src/components/Preview.jsx",
"src/utils/payload.js",
]
actual1 = {
"fileCount": len(project_files),
"hasComponentsDir": any(f.startswith("src/components/") for f in project_files),
"hasUtilsDir": any(f.startswith("src/utils/") for f in project_files),
"defaultPort": 5173,
}
expected1 = {
"fileCount": 9,
"hasComponentsDir": True,
"hasUtilsDir": True,
"defaultPort": 5173,
}
cases.append({
"name": "online_generated_project_layout",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: buildPayload utility across text, url, wifi, mailto modes
page.set_content("""<!DOCTYPE html>
<html><body><script>
function buildPayload(mode, data) {
if (mode === "url") {
const raw = (data.url || "").trim();
return /^https?:\\/\\//i.test(raw) ? raw : "https://" + raw;
}
if (mode === "wifi") {
return "WIFI:T:" + (data.auth || "WPA") + ";S:" + data.ssid + ";P:" + data.password + ";;";
}
if (mode === "email") {
return "mailto:" + data.to + "?subject=" + encodeURIComponent(data.subject || "");
}
return data.text || "";
}
window.__payloads = {
text: buildPayload("text", { text: "Hello React" }),
urlAutoHttps: buildPayload("url", { url: "example.com" }),
wifi: buildPayload("wifi", { auth: "WPA", ssid: "LabNet", password: "pass123" }),
email: buildPayload("email", { to: "dev@example.com", subject: "QR" })
};
</script></body></html>""")
actual2 = page.evaluate("() => window.__payloads")
expected2 = {
"text": "Hello React",
"urlAutoHttps": "https://example.com",
"wifi": "WIFI:T:WPA;S:LabNet;P:pass123;;",
"email": "mailto:dev@example.com?subject=QR",
}
cases.append({
"name": "payload_builder_modes",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3 & 4: Composed Controls + Preview React app with interactive mode/level switch
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
const defaultStyle = {{ size: 280, fgColor: "#111827", bgColor: "#ffffff", level: "M", margin: 2 }};
function buildPayload(mode) {{
if (mode === "wifi") return "WIFI:T:WPA;S:Studio;P:12345678;;";
return "https://example.com";
}}
function Controls({{ mode, level, onModeChange, onLevelChange }}) {{
return React.createElement(
"section", {{ id: "controls" }},
React.createElement("button", {{ id: "mode-url", onClick: () => onModeChange("url") }}, "网址"),
React.createElement("button", {{ id: "mode-wifi", onClick: () => onModeChange("wifi") }}, "WiFi"),
React.createElement("button", {{ id: "level-q", onClick: () => onLevelChange("Q") }}, "Q · 25%")
);
}}
function Preview({{ payload, style }}) {{
return React.createElement(
"section", {{ id: "preview" }},
React.createElement("p", {{ id: "meta" }}, style.size + " × " + style.size + " px · 容错 " + style.level + " · 边距 " + style.margin),
React.createElement("code", {{ id: "encoded" }}, payload)
);
}}
function App() {{
const [mode, setMode] = React.useState("url");
const [level, setLevel] = React.useState(defaultStyle.level);
const style = Object.assign({{}}, defaultStyle, {{ level }});
const payload = buildPayload(mode);
return React.createElement(
"div", null,
React.createElement(Controls, {{ mode, level, onModeChange: setMode, onLevelChange: setLevel }}),
React.createElement(Preview, {{ payload, style }})
);
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
actual3 = {
"meta": page.text_content("#meta"),
"encoded": page.text_content("#encoded"),
}
expected3 = {
"meta": "280 × 280 px · 容错 M · 边距 2",
"encoded": "https://example.com",
}
cases.append({
"name": "controls_and_preview_composition",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
page.click("#mode-wifi")
page.click("#level-q")
actual4 = {
"meta": page.text_content("#meta"),
"encoded": page.text_content("#encoded"),
}
expected4 = {
"meta": "280 × 280 px · 容错 Q · 边距 2",
"encoded": "WIFI:T:WPA;S:Studio;P:12345678;;",
}
cases.append({
"name": "interactive_mode_and_style_update",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
将纯数据格式拼接放入 `utils/payload.js` 便于独立单测与复用,`Controls` 专注收集用户输入,`Preview` 专注视图呈现,`App` 统一托管共享状态,符合 React 单向数据流与关注点分离原则。