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

JSX 渲染文章列表

核对 JSX 花括号表达式约束、动态属性绑定、array.map() 列表渲染与稳定 key 机制、三种条件渲染方式及 0 && 陷阱,以及完整博客首页卡片网格实测。

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

学完这一章,你能够

JSX 表达式插值与动态属性绑定

在 JSX 中,花括号 `{}` 是进入 JavaScript 求值上下文的入口,可嵌入变量、模板字符串、函数调用和三元运算符等能产出值的表达式,但不能直接写入 `if`/`for` 等控制流语句(例如 `{if (condition) ...}` 非法,需改为 `{condition ? 'A' : 'B'}`)。本站离线 Chromium 实测渲染标题、作者、日期与三元欢迎语,依次输出 `['BlueSky 前端笔记', '作者:小明', '当前时间:2026/05/15', '欢迎语:你好,小明']`。

动态 HTML 属性同样通过花括号绑定变量:`<img src={coverUrl} />` 与 `<a href={linkUrl}>` 直接接收 JS 变量,`class` 写作 `className="card active"`,`style` 接收驼峰属性对象(如 `{ color: '#42b883', fontSize: '16px' }`),事件属性采用驼峰名并传入函数引用(`onClick={fn}`)。本站实测验证 `href="/post/1"`、`class="card active"`、计算颜色 `rgb(66, 184, 131)` 与字号 `16px`,点击按钮事件正常触发。

array.map() 列表渲染与稳定 key 的重要性

React 不提供模板指令,列表渲染直接使用原生 JavaScript 的 `articles.map(...)` 将每条数据映射为对应 JSX 卡片节点。遍历返回的每个顶层元素都必须附加唯一且稳定的 `key` 属性(推荐数据主键 `article.id`),以便 React 在 Diff 协调时精确追踪节点增删与移动;若缺失 `key` 或使用数组下标 `index`,在头部插入、删除或重排列表时就地复用 DOM 会引发输入框等局部状态错位。本站离线 Chromium 实测在 3 篇文章的首项输入框填入 `React 笔记` 后再向头部插入新文章:采用 `article.id` 作为 `key` 时 `React 笔记` 准确跟随原首篇文章移至第 2 位,而采用数组 `index` 作为 `key` 时 `React 笔记` 错误滞留在新插入的置顶项上。

三种条件渲染方式与 && 数字 0 陷阱

JSX 常用三种条件渲染手段:二选一分支使用三元表达式 `{cond ? <A /> : <B />}`;“满足即显示、否则不渲染”使用逻辑与短路 `{cond && <A />}`;多分支复杂判断则提前在 `return` 前用 `if/else` 组织好 JSX 变量。特别需要防范 `&&` 的假值陷阱:JavaScript 对 `0 && <A />` 返回数字 `0`,React 会将数字 `0` 原样渲染到页面上,因此左侧务必转为显式布尔值(写 `{list.length > 0 && ...}` 而非 `{list.length && ...}`)。本站实测空数组时未转布尔的 `list.length && '有文章'` 渲染出字符 `'0'`,而 `list.length > 0 && '有文章'` 渲染为空字符串 `''`。

实战:数据驱动的博客首页卡片网格

结合表达式插值、动态属性、`map()` + `key` 与三元条件渲染,即可将静态骨架升级为动态博客首页:文章数组为空时渲染 `.empty-tip` 空态提示,非空时通过 CSS Grid(`.article-grid`)渲染每篇文章的封面、分类标签、标题、摘要与日期。本站离线 Chromium 实测 3 篇示例数据生成 `display: grid` 布局及 3 张卡片(分类 `['React', 'JavaScript', 'CSS']`),切换为空数组后卡片清零并显示 `还没有文章,敬请期待。`。

JSX 动态属性与 HTML 原生属性写法对照

HTML 原生写法JSX 对应写法核心说明
class="btn"className="btn"class 为 JS 保留关键字
style="color: red"style={{ color: 'red' }}接收样式对象,属性名使用小驼峰
src="xxx"src={variable}动态属性值用花括号绑定表达式
onclick="fn()"onClick={fn}事件名小驼峰并传入函数引用

列表渲染 key 取值策略与影响对比

key 取值策略渲染与状态影响
唯一稳定主键 id(推荐)准确识别节点增删移动,保持局部 DOM 状态与高效 Diff
数组下标 index头部插入、删除或排序时复用错位,易致表单输入内容串项
省略 key 属性开发环境触发控制台警告,默认按索引就地更新且协调开销高

React 三种条件渲染写法与适用场景

实现方式典型语法适用场景
三元运算符 ? :{cond ? <A /> : <B />}需要在两个互斥视图分支中二选一
逻辑与短路 &&{cond && <A />}单分支按需显隐,左侧务必确保为布尔值以防渲染 0
return 前提前 if 组装在 return 之前按条件赋值 JSX 变量分支超过两路或嵌套较复杂时提升可读性

离线 Chromium 实测 JSX 表达式、id vs index key 协调错位、0 && 陷阱与博客首页卡片网格

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对动态属性与样式计算值、头插列表时 id key 保持输入框归属而 index key 错位、0 && 渲染字符 '0' 与安全布尔守卫,以及 3 卡片网格与空态切换。
离线 Chromium 实测 JSX 表达式、id vs index key 协调错位、0 && 陷阱与博客首页卡片网格

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

当前源码 SHA256:f7a6c03f7208b03ef90a8c3f38e285a6a7ecf5e2e486c2d3c5cda12251159c7f

下载本站示例源码

本地运行

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

下载JSX 渲染文章列表实验

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

ZIP SHA256:8d62cb692cc9a82943a27d991aeb6b5e14ec89ac72f607e4691eb0f4bf83226e

常见错误与边界

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

练习与解答

为什么在 JSX 中写 `{articles.length && <ArticleList />}` 存在隐患?应如何改写?

展开参考解答

当 `articles.length` 为数字 `0` 时,`&&` 短路表达式的求值结果是 `0` 而非 `false`,React 会把数字 `0` 渲染成页面上的可见文本;应改写为 `{articles.length > 0 && <ArticleList />}` 或使用三元表达式。

规范与官方依据