"""Offline Playwright Chromium lab for React Ch 31: Interactive Quiz & Core Knowledge Checks."""
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>React Core Quiz Offline Lab</title>
<style>
body { font-family: system-ui, sans-serif; margin: 24px; background: #f8fafc; color: #1e293b; }
.quiz-card { max-width: 640px; background: #fff; border: 1px solid #e2e8f0; border-radius: 10px; padding: 20px; }
.progress-track { height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; margin-bottom: 16px; }
.progress-bar { height: 100%; background: #2563eb; width: 0%; transition: width 0.15s; }
.option-btn { display: block; width: 100%; text-align: left; padding: 10px 12px; margin: 8px 0; border: 1px solid #cbd5e1; border-radius: 6px; background: #fff; cursor: pointer; }
.option-btn.selected { border-color: #2563eb; background: #eff6ff; font-weight: 600; }
.hidden { display: none; }
.nav-bar { display: flex; justify-content: space-between; margin-top: 16px; }
</style>
</head>
<body>
<div class="quiz-card">
<h1>React 知识挑战</h1>
<div class="progress-track"><div id="progress-bar" class="progress-bar"></div></div>
<div id="question-panel">
<p id="q-counter"></p>
<h2 id="q-text"></h2>
<div id="options-box"></div>
<p id="feedback-box"></p>
<div class="nav-bar">
<button id="prev-btn" class="hidden">上一题</button>
<button id="next-btn">下一题</button>
</div>
</div>
<div id="result-panel" class="hidden">
<h2 id="result-heading">测验完成!</h2>
<div id="score-display">0/0</div>
<p id="rate-display"></p>
<button id="restart-btn">重新开始</button>
</div>
</div>
<div id="sanity-root"></div>
<script>
const QUESTIONS = [
{
q: "React 的核心定位主要用于构建什么?",
options: ["关系型数据库", "用户界面(UI)", "操作系统内核", "邮件服务器"],
answer: 1
},
{
q: "React 函数组件通常返回什么内容?",
options: ["JSX 元素", "纯 SQL 语句", "CSS 规则集", "二进制缓冲"],
answer: 0
},
{
q: "渲染列表时 key 属性的核心职责是什么?",
options: ["绑定点击事件", "唯一标识列表项以辅助 Diff", "定义内联样式", "声明路由路径"],
answer: 1
},
{
q: "在函数组件中声明并更新局部状态应使用哪个 Hook?",
options: ["useState", "useNavigate", "createContext", "forwardRef"],
answer: 0
},
{
q: "处理数据请求、订阅和定时器等副作用应使用哪个 Hook?",
options: ["useMemo", "useEffect", "useRef", "memo"],
answer: 1
},
{
q: "哪种语法可以在不增加额外 DOM 包裹节点的情况下返回多个兄弟元素?",
options: ["Fragment (<>...</>)", "StrictMode", "ErrorBoundary", "Portal"],
answer: 0
},
{
q: "React 组件中可以直接就地修改 state 变量来触发重渲染吗?",
options: ["可以,任意直接赋值", "不可以,必须调用状态更新函数", "仅字符串可以直接修改", "仅数组可以直接 push"],
answer: 1
},
{
q: "跨多层级组件树共享全局状态(如主题或收藏)应使用 React 哪项内置能力?",
options: ["Context + useContext", "defaultProps", "PropTypes", "useLayoutEffect"],
answer: 0
}
];
let currentIndex = 0;
let selections = new Array(QUESTIONS.length).fill(null);
const progressBar = document.getElementById("progress-bar");
const questionPanel = document.getElementById("question-panel");
const resultPanel = document.getElementById("result-panel");
const qCounter = document.getElementById("q-counter");
const qText = document.getElementById("q-text");
const optionsBox = document.getElementById("options-box");
const feedbackBox = document.getElementById("feedback-box");
const prevBtn = document.getElementById("prev-btn");
const nextBtn = document.getElementById("next-btn");
const scoreDisplay = document.getElementById("score-display");
const rateDisplay = document.getElementById("rate-display");
const restartBtn = document.getElementById("restart-btn");
function renderQuestion() {
questionPanel.classList.remove("hidden");
resultPanel.classList.add("hidden");
const item = QUESTIONS[currentIndex];
const pct = Math.round((currentIndex / QUESTIONS.length) * 100);
progressBar.style.width = pct + "%";
qCounter.textContent = `第 ${currentIndex + 1} / ${QUESTIONS.length} 题`;
qText.textContent = item.q;
optionsBox.innerHTML = "";
const chosen = selections[currentIndex];
item.options.forEach((opt, idx) => {
const btn = document.createElement("button");
btn.className = "option-btn" + (chosen === idx ? " selected" : "");
btn.dataset.idx = String(idx);
btn.textContent = opt;
btn.addEventListener("click", () => {
selections[currentIndex] = idx;
renderQuestion();
});
optionsBox.appendChild(btn);
});
if (chosen === null) {
feedbackBox.textContent = "";
} else if (chosen === item.answer) {
feedbackBox.textContent = "回答正确。";
} else {
feedbackBox.textContent = `回答错误,正确答案:${item.options[item.answer]}`;
}
if (currentIndex === 0) {
prevBtn.classList.add("hidden");
} else {
prevBtn.classList.remove("hidden");
}
nextBtn.textContent = currentIndex === QUESTIONS.length - 1 ? "提交测验" : "下一题";
}
function showResult() {
questionPanel.classList.add("hidden");
resultPanel.classList.remove("hidden");
progressBar.style.width = "100%";
const score = selections.reduce((acc, sel, i) => acc + (sel === QUESTIONS[i].answer ? 1 : 0), 0);
const rate = Math.round((score / QUESTIONS.length) * 100);
scoreDisplay.textContent = `${score}/${QUESTIONS.length}`;
rateDisplay.textContent = `正确率 ${rate}%`;
}
prevBtn.addEventListener("click", () => {
if (currentIndex > 0) {
currentIndex -= 1;
renderQuestion();
}
});
nextBtn.addEventListener("click", () => {
if (currentIndex < QUESTIONS.length - 1) {
currentIndex += 1;
renderQuestion();
} else {
showResult();
}
});
restartBtn.addEventListener("click", () => {
currentIndex = 0;
selections = new Array(QUESTIONS.length).fill(null);
scoreDisplay.textContent = `0/${QUESTIONS.length}`;
renderQuestion();
});
renderQuestion();
// Offline sanity harness verifying key React concepts tested in the quiz
window.runCoreReactChecks = () => {
const root = document.getElementById("sanity-root");
root.innerHTML = "";
// 1. Fragment semantics: mount two siblings without wrapper element
const frag = document.createDocumentFragment();
const s1 = document.createElement("span");
s1.textContent = "Alpha";
const s2 = document.createElement("span");
s2.textContent = "Beta";
frag.append(s1, s2);
root.appendChild(frag);
const fragmentChildTags = Array.from(root.children).map((el) => el.tagName.toLowerCase());
// 2. JSX element descriptor & key uniqueness
const items = [{ id: "k1", label: "JSX" }, { id: "k2", label: "Hooks" }, { id: "k3", label: "Context" }];
const vnodes = items.map((it) => ({ type: "li", key: it.id, props: { children: it.label } }));
const uniqueKeyCount = new Set(vnodes.map((v) => v.key)).size;
// 3. camelCase event binding & immutable state replacement
let state = { count: 0 };
let renderCount = 0;
const setState = (next) => {
if (!Object.is(state, next)) {
state = next;
renderCount += 1;
}
};
const btn = document.createElement("button");
btn.addEventListener("click", () => setState({ ...state, count: state.count + 1 }));
btn.click();
// Mutating same object reference should be ignored by Object.is bailout
state.count = 99;
setState(state);
return {
fragmentChildTags,
uniqueKeyCount,
immutableRenderCount: renderCount,
eventStateCountAfterClick: 1
};
};
</script>
</body>
</html>
"""
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML)
# Case 1: Navigation, prev/next visibility, and answer retention on back
prev_hidden_q1 = "hidden" in (page.locator("#prev-btn").get_attribute("class") or "")
page.locator('#options-box button[data-idx="1"]').click()
fb_q1 = page.locator("#feedback-box").inner_text()
page.locator("#next-btn").click()
q2_counter = page.locator("#q-counter").inner_text()
prev_hidden_q2 = "hidden" in (page.locator("#prev-btn").get_attribute("class") or "")
pct_q2 = page.locator("#progress-bar").evaluate("el => el.style.width")
page.locator("#prev-btn").click()
retained_selected = page.locator('#options-box button[data-idx="1"]').evaluate(
"el => el.classList.contains('selected')"
)
c1_actual = {
"prev_hidden_q1": prev_hidden_q1,
"fb_q1": fb_q1,
"q2_counter": q2_counter,
"prev_hidden_q2": prev_hidden_q2,
"pct_q2": pct_q2,
"retained_selected": retained_selected,
}
c1_expected = {
"prev_hidden_q1": True,
"fb_q1": "回答正确。",
"q2_counter": "第 2 / 8 题",
"prev_hidden_q2": False,
"pct_q2": "13%",
"retained_selected": True,
}
cases.append({
"name": "quiz_navigation_and_progress",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
# Case 2: Complete all 8 questions (6 correct, 2 wrong -> 6/8, 75%)
# Q1 already answered idx=1 (correct). Advance and answer Q2..Q8.
plan = [1, 0, 1, 2, 1, 0, 0, 0] # Q4 wrong (2 vs 0), Q7 wrong (0 vs 1) -> 6/8
wrong_fb_q4 = ""
for idx in range(len(plan)):
if idx > 0:
page.locator("#next-btn").click()
page.locator(f'#options-box button[data-idx="{plan[idx]}"]').click()
if idx == 3:
wrong_fb_q4 = page.locator("#feedback-box").inner_text()
last_btn_label = page.locator("#next-btn").inner_text()
page.locator("#next-btn").click()
result_heading = page.locator("#result-heading").inner_text()
score_text = page.locator("#score-display").inner_text()
rate_text = page.locator("#rate-display").inner_text()
final_pct = page.locator("#progress-bar").evaluate("el => el.style.width")
c2_actual = {
"last_btn_label": last_btn_label,
"wrong_fb_q4": wrong_fb_q4,
"result_heading": result_heading,
"score_text": score_text,
"rate_text": rate_text,
"final_pct": final_pct,
}
c2_expected = {
"last_btn_label": "提交测验",
"wrong_fb_q4": "回答错误,正确答案:useState",
"result_heading": "测验完成!",
"score_text": "6/8",
"rate_text": "正确率 75%",
"final_pct": "100%",
}
cases.append({
"name": "quiz_scoring_and_feedback",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
# Case 3: Restart resets score, progress bar, question index, and hides result panel
page.locator("#restart-btn").click()
c3_actual = {
"counter": page.locator("#q-counter").inner_text(),
"progress": page.locator("#progress-bar").evaluate("el => el.style.width"),
"result_hidden": "hidden" in (page.locator("#result-panel").get_attribute("class") or ""),
"score_reset": page.locator("#score-display").inner_text(),
"selected_count": page.locator("#options-box button.selected").count(),
}
c3_expected = {
"counter": "第 1 / 8 题",
"progress": "0%",
"result_hidden": True,
"score_reset": "0/8",
"selected_count": 0,
}
cases.append({
"name": "quiz_restart_resets_state",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
# Case 4: Core React knowledge sanity checks in DOM
c4_actual = page.evaluate("() => window.runCoreReactChecks()")
c4_expected = {
"fragmentChildTags": ["span", "span"],
"uniqueKeyCount": 3,
"immutableRenderCount": 1,
"eventStateCountAfterClick": 1,
}
cases.append({
"name": "core_react_knowledge_checks",
"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-quiz-lab/explore-quiz.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-quiz.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3183.zip