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

React 测验

核对 React 核心概念测验范围(JSX、组件与 Props/State、Hooks、虚拟 DOM、Router、Context、性能优化与错误边界)及离线无头 Chromium 交互计分实测。

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

学完这一章,你能够

React 测验定位与核心考点覆盖

本章通过互动式单选题检验 React 知识掌握程度,核心考点横跨五大主题:一是定位与渲染模型(前端 UI 库定位、组件返回 JSX 元素、大写组件命名、虚拟 DOM 差异更新、`Fragment` 支持多根节点、`StrictMode` 开发期自检);二是数据流与事件(父传子单向 `props`、`defaultProps` 与 `PropTypes`、只读 `state` 与 `setState`/更新函数、`onClick={handleClick}` 驼峰事件与回调传递);三是条件与列表渲染(三元运算符、`Array.prototype.map` 与唯一 `key` 标识);四是 Hooks 与生命周期(`useState`、`useEffect`、`useLayoutEffect` 同步执行差异、`useRef`、`useContext`、`memo`/`useCallback`/`useMemo` 性能缓存及类组件 `componentDidMount` 挂载时机);五是工程进阶能力(React Router、`Context` 全局共享、`forwardRef`、`Suspense` 异步加载与 `Error Boundary` 错误捕获)。

交互测验流程围绕题目切换、即时判题、进度条更新、结算展示(“测验完成!”与最终得分)以及“重新开始”重置展开。本站严格不执行来源页面外部与内联脚本,而在离线无头 Chromium 中独立构建 8 道核心代表题测验程序完成实测:首题默认隐藏“上一题”按钮,选择正确项后立即提示 `回答正确。`,切至第 2 题进度条推进至 `13%` 且回退第 1 题保留选中状态;完成全部 8 题(6 对 2 错)后末题按钮切换为 `提交测验`,提交后显示 `测验完成!`、`6/8` 与 `正确率 75%`(进度 `100%`);点击“重新开始”后题目归位至 `第 1 / 8 题`、进度归 `0%`、得分重置为 `0/8`;同步运行的核心机制自检确认 `Fragment` 无包裹节点挂载两个 `span`、3 项列表 `key` 唯一、不可变状态更新与 `Object.is` 拦截生效(渲染计数 `1`)。

离线 Chromium 实测独立 React 知识测验交互、计分、重开与核心特性自检

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对 8 题测验的上/下一题导航与选中态保留、6/8(75%)得分结算、重新开始重置归零,以及 Fragment/key/不可变状态核心机制自检通过。
离线 Chromium 实测独立 React 知识测验交互、计分、重开与核心特性自检

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

当前源码 SHA256:0442f3970c6b081d00e6ea69774879fe2a38b0a7981249389e0f3d61f04e7a55

下载本站示例源码

本地运行

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

下载React 测验实验

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

ZIP SHA256:afad4fbc00a2557963690c8ed8aac9f1d3fdaf1172a2130fdb68facca382cc8a

常见错误与边界

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

练习与解答

在 React 测验中,为什么 `useLayoutEffect` 与 `useEffect` 的执行时机不同?列表渲染时为何必须提供稳定 `key`?

展开参考解答

`useEffect` 在浏览器完成绘制后异步触发,不阻塞视觉渲染;`useLayoutEffect` 在 DOM 变更后、浏览器绘制前同步执行,适合需要读取布局并立即同步修正样式的场景。列表渲染中稳定 `key` 用于帮助 React 精确对应前后两次渲染的同一元素,避免元素重排或增删时状态错位与低效重建。

规范与官方依据