"""Offline Playwright Chromium lab for React Ch 33: JSX Expressions, Attrs, map/key & Conditional Rendering."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>JSX Template Syntax Lab</title>
<style>
.article-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 24px; }
.article-card { background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 12px rgba(0,0,0,0.08); }
.card-category { display: inline-block; padding: 2px 10px; background: #e3f2fd; color: #1976d2; border-radius: 12px; font-size: 12px; }
.empty-tip { text-align: center; color: #999; padding: 40px 0; }
</style>
</head>
<body>
<section id="sec-expr"></section>
<section id="sec-key-id"></section>
<section id="sec-key-idx"></section>
<section id="sec-cond"></section>
<section id="sec-home"></section>
<script>
const TINY_SVG = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='20'%3E%3Crect width='40' height='20' fill='%231976d2'/%3E%3C/svg%3E";
// 1. Expressions & dynamic attributes
window.runExprAndAttrLab = () => {
const blogTitle = "BlueSky 前端笔记";
const author = "小明";
const fixedDate = "2026/05/15";
const coverUrl = TINY_SVG;
const linkUrl = "/post/1";
let clicked = false;
const box = document.getElementById("sec-expr");
box.innerHTML = "";
const wrap = document.createElement("div");
const h1 = document.createElement("h1");
h1.textContent = blogTitle;
const pAuthor = document.createElement("p");
pAuthor.textContent = `作者:${author}`;
const pDate = document.createElement("p");
pDate.textContent = `当前时间:${fixedDate}`;
const pWelcome = document.createElement("p");
pWelcome.textContent = `欢迎语:${author ? `你好,${author}` : "欢迎访客"}`;
const img = document.createElement("img");
img.setAttribute("src", coverUrl);
img.setAttribute("alt", "文章封面");
const link = document.createElement("a");
link.setAttribute("href", linkUrl);
link.textContent = "阅读全文";
const card = document.createElement("div");
card.className = "card active";
card.textContent = "卡片内容";
const styled = document.createElement("div");
Object.assign(styled.style, { color: "#42b883", fontSize: "16px" });
styled.textContent = "绿色文字";
const btn = document.createElement("button");
btn.textContent = "触发事件";
btn.addEventListener("click", () => { clicked = true; });
wrap.append(h1, pAuthor, pDate, pWelcome, img, link, card, styled, btn);
box.appendChild(wrap);
btn.click();
return {
lines: [h1.textContent, pAuthor.textContent, pDate.textContent, pWelcome.textContent],
imgAlt: img.getAttribute("alt"),
linkHref: link.getAttribute("href"),
cardClass: card.getAttribute("class"),
styledColor: getComputedStyle(styled).color,
styledFontSize: getComputedStyle(styled).fontSize,
eventFired: clicked
};
};
// 2. Stable id key vs index key reconciliation when prepending an item
function reconcileList(container, items, getKey) {
const existing = new Map();
Array.from(container.children).forEach((node) => {
existing.set(node.dataset.rkey, node);
});
const nextNodes = items.map((item, idx) => {
const key = String(getKey(item, idx));
let row = existing.get(key);
if (!row) {
row = document.createElement("div");
row.dataset.rkey = key;
const lbl = document.createElement("span");
const inp = document.createElement("input");
row.append(lbl, inp);
}
row.querySelector("span").textContent = item.title;
return row;
});
container.replaceChildren(...nextNodes);
}
window.runKeyReconcileLab = () => {
const initial = [
{ id: 1, title: "React 入门完全指南" },
{ id: 2, title: "JavaScript 异步编程详解" },
{ id: 3, title: "CSS Grid 布局实战" }
];
const prepended = [{ id: 99, title: "新增置顶文章" }, ...initial];
const idHost = document.getElementById("sec-key-id");
const idxHost = document.getElementById("sec-key-idx");
reconcileList(idHost, initial, (a) => a.id);
reconcileList(idxHost, initial, (_, i) => i);
// Type a note into the first item ("React 入门完全指南") in both lists
idHost.children[0].querySelector("input").value = "React 笔记";
idxHost.children[0].querySelector("input").value = "React 笔记";
// Prepend a new item at index 0
reconcileList(idHost, prepended, (a) => a.id);
reconcileList(idxHost, prepended, (_, i) => i);
const snapshot = (host) =>
Array.from(host.children).map((row) => ({
title: row.querySelector("span").textContent,
note: row.querySelector("input").value
}));
return {
withIdKey: snapshot(idHost),
withIndexKey: snapshot(idxHost)
};
};
// 3. Conditional rendering: ternary, &&, early if, and the numeric 0 && trap
window.runConditionalLab = () => {
function renderView(isLoading, list, safeBoolGuard) {
const nodes = [];
// Ternary
nodes.push(isLoading ? "加载中,请稍候..." : "加载完成!");
// && short-circuit
if (list.length === 0) nodes.push("还没有文章,敬请期待。");
// Early if/else block
let statusBanner;
if (isLoading) statusBanner = "STATUS:LOADING";
else if (list.length === 0) statusBanner = "STATUS:EMPTY";
else statusBanner = `STATUS:COUNT_${list.length}`;
nodes.push(statusBanner);
// Simulate React child rendering of {list.length && <p>有文章</p>} vs {list.length > 0 && <p>有文章</p>}
const shortCircuitVal = safeBoolGuard ? (list.length > 0 && "有文章") : (list.length && "有文章");
const renderedTrapChild =
shortCircuitVal === false || shortCircuitVal === null || shortCircuitVal === undefined
? ""
: String(shortCircuitVal);
return { nodes, renderedTrapChild };
}
return {
loadingCase: renderView(true, [], true),
emptyUnsafeTrap: renderView(false, [], false),
emptySafeGuard: renderView(false, [], true),
nonEmptyCase: renderView(false, [{ id: 1, title: "React" }], true)
};
};
// 4. Full Blog Homepage article cards & empty fallback
const HOME_ARTICLES = [
{ id: 1, title: "React 入门完全指南", summary: "从零开始学习 React Hooks,涵盖 useState、useEffect 等核心概念。", date: "2024-05-10", category: "React", cover: TINY_SVG },
{ id: 2, title: "JavaScript 异步编程详解", summary: "一文搞懂 Promise、async/await、事件循环与微任务队列。", date: "2024-05-08", category: "JavaScript", cover: TINY_SVG },
{ id: 3, title: "CSS Grid 布局实战", summary: "用 CSS Grid 轻松实现复杂的响应式布局。", date: "2024-05-05", category: "CSS", cover: TINY_SVG }
];
window.renderHomePage = (articles) => {
const host = document.getElementById("sec-home");
host.innerHTML = "";
if (articles.length === 0) {
const tip = document.createElement("p");
tip.className = "empty-tip";
tip.textContent = "还没有文章,敬请期待。";
host.appendChild(tip);
return { cardCount: 0, emptyTip: tip.textContent, gridDisplay: null };
}
const grid = document.createElement("div");
grid.className = "article-grid";
articles.forEach((a) => {
const card = document.createElement("div");
card.className = "article-card";
card.dataset.id = String(a.id);
card.innerHTML = `
<img src="${a.cover}" alt="${a.title}" class="card-cover" />
<div class="card-content">
<span class="card-category">${a.category}</span>
<h3 class="card-title">${a.title}</h3>
<p class="card-summary">${a.summary}</p>
<span class="card-date">${a.date}</span>
</div>`;
grid.appendChild(card);
});
host.appendChild(grid);
return {
cardCount: grid.querySelectorAll(".article-card").length,
titles: Array.from(grid.querySelectorAll(".card-title")).map((el) => el.textContent),
categories: Array.from(grid.querySelectorAll(".card-category")).map((el) => el.textContent),
gridDisplay: getComputedStyle(grid).display
};
};
</script>
</body>
</html>
"""
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML)
c1_actual = page.evaluate("() => window.runExprAndAttrLab()")
c1_expected = {
"lines": ["BlueSky 前端笔记", "作者:小明", "当前时间:2026/05/15", "欢迎语:你好,小明"],
"imgAlt": "文章封面",
"linkHref": "/post/1",
"cardClass": "card active",
"styledColor": "rgb(66, 184, 131)",
"styledFontSize": "16px",
"eventFired": True,
}
cases.append({
"name": "jsx_expression_and_attr_binding",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
c2_actual = page.evaluate("() => window.runKeyReconcileLab()")
c2_expected = {
"withIdKey": [
{"title": "新增置顶文章", "note": ""},
{"title": "React 入门完全指南", "note": "React 笔记"},
{"title": "JavaScript 异步编程详解", "note": ""},
{"title": "CSS Grid 布局实战", "note": ""},
],
"withIndexKey": [
{"title": "新增置顶文章", "note": "React 笔记"},
{"title": "React 入门完全指南", "note": ""},
{"title": "JavaScript 异步编程详解", "note": ""},
{"title": "CSS Grid 布局实战", "note": ""},
],
}
cases.append({
"name": "map_list_rendering_and_stable_key",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
c3_actual = page.evaluate("() => window.runConditionalLab()")
c3_expected = {
"loadingCase": {
"nodes": ["加载中,请稍候...", "还没有文章,敬请期待。", "STATUS:LOADING"],
"renderedTrapChild": "",
},
"emptyUnsafeTrap": {
"nodes": ["加载完成!", "还没有文章,敬请期待。", "STATUS:EMPTY"],
"renderedTrapChild": "0",
},
"emptySafeGuard": {
"nodes": ["加载完成!", "还没有文章,敬请期待。", "STATUS:EMPTY"],
"renderedTrapChild": "",
},
"nonEmptyCase": {
"nodes": ["加载完成!", "STATUS:COUNT_1"],
"renderedTrapChild": "有文章",
},
}
cases.append({
"name": "conditional_rendering_and_zero_trap",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
c4_actual = {
"populated": page.evaluate("() => window.renderHomePage(HOME_ARTICLES)"),
"empty": page.evaluate("() => window.renderHomePage([])"),
}
c4_expected = {
"populated": {
"cardCount": 3,
"titles": ["React 入门完全指南", "JavaScript 异步编程详解", "CSS Grid 布局实战"],
"categories": ["React", "JavaScript", "CSS"],
"gridDisplay": "grid",
},
"empty": {
"cardCount": 0,
"emptyTip": "还没有文章,敬请期待。",
"gridDisplay": None,
},
}
cases.append({
"name": "blog_homepage_cards_and_empty_state",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/react-blog-template-syntax-lab/explore-blog-template-syntax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-template-syntax.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3160.zip
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip