React JSX
核对 JSX 编译本质、严格标签与属性规则、表达式/条件/列表渲染、内联样式与 CSS Modules 作用域隔离及数组展开的离线 Chromium 实测。
学完这一章,你能够
- 核对 JSX 编译本质、严格标签与属性规则、表达式/条件/列表渲染、内联样式与 CSS Modules 作用域隔离及数组展开的离线 Chromium 实测。
JSX 本质与核心优势
JSX(JavaScript XML)是嵌入在 JavaScript 中的类 XML 语法扩展,用于以接近 HTML 的直观方式描述组件结构与交互。使用 JSX 并非强制,但它具备显著工程优势:编译为原生 JS 调用后便于打包优化且运行高效;搭配 TypeScript 可在编译阶段提前暴露类型错误;在模板中灵活穿插 JS 表达式让界面编写简洁清晰。其本质既非 HTML 也非普通字符串,而会经由 Babel 或 Vite(React 17+ 自动运行时为 `_jsx`、经典运行时为 `React.createElement`)转译为创建元素对象的函数调用。
例如 `const element = <h1>Hello, world!</h1>` 在运行前会被转译为生成普通描述对象的表达式。React DOM 根据这些轻量对象同步浏览器真实 DOM,并通过 `ReactDOM.createRoot(document.getElementById('root')).render(element)`(旧版写法为 `ReactDOM.render`)将元素挂载到根容器中。
JSX 虽形似 HTML,但遵循严格语法规则:所有标签必须显式闭合,空元素如 `<br />`、`<img ... />` 必须自闭合;因 `class` 与 `for` 是 JavaScript 保留字,JSX 改用 `className` 与 `htmlFor`;自定义组件必须以大写字母开头(如 `<Card />`),小写标签会被当作原生 HTML 标签处理;注释需写在花括号内 `{/* 注释内容 */}`;组件 `return` 必须只有单一根节点,可用空碎片 `<>...</>`(`Fragment`)包裹兄弟元素而不产生多余外层 DOM。本站实测 Fragment 直接输出 5 个子元素,`className` 映射为 `class="title"`,`htmlFor` 映射为 `for="email-input"`,大写 `Badge` 渲染为 `SPAN` 而小写 `badge` 保留为 `BADGE`,且注释节点数为 `0`。
表达式嵌入、条件分支、列表与数组展开
JSX 最核心的能力是通过花括号 `{}` 嵌入任意有效的 JavaScript 表达式(如变量、函数调用、算术运算),但不能直接放置 `if`/`for` 等语句。本站实测 `{1 + 1}` 输出 `2`,`{2 + 3 * 5}` 按运算优先级输出 `17`。
在 JSX 内部实现条件渲染需借助三元运算符(`cond ? a : b`)或逻辑与短路(`cond && <El />`),复杂的 `if/else` 逻辑应留在组件函数体中处理。实测三元表达式在 `i === 1` 时输出 `True!`,否则输出 `False`;`count > 0 && ...` 在 `count === 0` 时不渲染节点,在 `count === 3` 时输出 `你有 3 条未读消息`。
JSX 允许直接插入元素数组并自动展开所有成员;动态列表通常使用 `Array.prototype.map()` 生成,并为每一项提供稳定且唯一的 `key`(最佳实践是业务数据主键 `item.id`)。缺失 `key` 会触发告警,用数组下标 `index` 作为 `key` 在列表重排或头部插入时会引发状态错乱与无效重渲染。实测数组 `[<h1>, <h2>]` 自动展开为 `["H1", "H2"]`,水果列表稳定渲染 `["苹果", "香蕉", "橙子"]` 且绑定键值 `["1", "2", "3"]`。
样式处理、自定义属性与独立文件引入
基础样式方案分为内联样式与 CSS Modules。内联样式通过 `style={{ ... }}` 传入驼峰命名对象(如 `backgroundColor`、`fontSize`),优点是便于基于变量动态计算,缺点是难以维护复杂样式与伪类;React 会自动为大多数数值型尺寸属性追加 `px` 单位,而对无单位属性(如 `opacity`)保持原值。本站通过 `getComputedStyle` 实测 `fontSize: 100` 计算为 `100px`、`color: '#FF0000'` 为 `rgb(255, 0, 0)`、`borderRadius: 8` 为 `8px`、`opacity: 0.5` 为 `0.5`。
工程项目更推荐使用 CSS Modules(Vite 开箱支持 `.module.css` 文件):导入样式对象 `import styles from './Card.module.css'` 后通过 `className={styles.container}` 绑定,构建工具会自动生成带哈希后缀的作用域类名以隔离样式、杜绝全局命名冲突。实测应用哈希类名 `Card_container__9f2a` 与 `Card_title__4c1b` 后卡片宽度计算为 `300px` 且类名精准生效。
嵌套多个标签时可用 `<div>` 或 `<>...</>` 包裹,自定义 HTML 数据属性应遵循 `data-` 前缀规范(如 `data-myattribute="somevalue"`,实测可由 `getAttribute` 准确读取);花括号注释 `{/* ... */}` 不会输出到最终 DOM。JSX 代码既可内联也可拆分为独立文件(如 `helloworld_react.js`),在传统静态页原型中通过 `<script type="text/babel" src="...">` 转译加载,而在现代工程中应交由 Vite/Babel 在构建阶段预编译。实测独立模块编译产物成功挂载 `<h1 class="foo">Hello, world</h1>`。
离线 Chromium 验证 JSX 语法规则、表达式分支、内联样式/CSS Modules 与数组展开
"""Offline Chromium lab for React Ch 12: jsx."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>React JSX Lab</title>
<style>
.Card_container__9f2a { width: 300px; border: 1px solid rgb(204, 204, 204); border-radius: 12px; }
.Card_title__4c1b { color: rgb(51, 51, 51); }
</style>
</head>
<body>
<div id="rules-root"></div>
<div id="expr-root"></div>
<div id="style-root"></div>
<div id="array-root"></div>
<div id="sep-root"></div>
<script>
'use strict';
const Fragment = Symbol('react.fragment');
const UNITLESS = new Set(['opacity', 'zIndex', 'fontWeight', 'lineHeight', 'flexGrow', 'flexShrink']);
function createElement(type, props, ...children) {
const flat = [];
function push(c) {
if (Array.isArray(c)) { c.forEach(push); return; }
if (c === null || c === undefined || typeof c === 'boolean') return;
flat.push(c);
}
children.forEach(push);
return { $$typeof: 'react.element', type, key: props && props.key !== undefined ? String(props.key) : null, props: Object.assign({}, props || {}, { children: flat }) };
}
function renderNode(vnode) {
if (typeof vnode === 'string' || typeof vnode === 'number') {
return document.createTextNode(String(vnode));
}
if (vnode.type === Fragment) {
const frag = document.createDocumentFragment();
vnode.props.children.forEach(c => frag.appendChild(renderNode(c)));
return frag;
}
if (typeof vnode.type === 'function') {
return renderNode(vnode.type(vnode.props));
}
const el = document.createElement(vnode.type);
for (const [k, v] of Object.entries(vnode.props)) {
if (k === 'children' || k === 'key' || v === undefined || v === null) continue;
if (k === 'className') el.setAttribute('class', v);
else if (k === 'htmlFor') el.setAttribute('for', v);
else if (k === 'style' && typeof v === 'object') {
for (const [sk, sv] of Object.entries(v)) {
const val = (typeof sv === 'number' && !UNITLESS.has(sk)) ? (sv + 'px') : String(sv);
el.style[sk] = val;
}
} else {
el.setAttribute(k, String(v));
}
}
vnode.props.children.forEach(c => el.appendChild(renderNode(c)));
return el;
}
function createRoot(container) {
return {
render(el) {
container.innerHTML = '';
container.appendChild(renderNode(el));
}
};
}
window.runLab = function () {
// Case 1: JSX syntax rules (Fragment, className, htmlFor, data-*, Uppercase component vs lowercase tag, comment ignored)
function Badge({ text }) {
return createElement('span', { className: 'badge' }, text);
}
const rulesRoot = document.getElementById('rules-root');
createRoot(rulesRoot).render(
createElement(
Fragment, null,
createElement('h1', { className: 'title' }, 'JSX 语法规则演示'),
createElement('label', { htmlFor: 'email-input' }, '邮箱'),
createElement('p', { 'data-myattribute': 'somevalue' }, '自定义数据属性'),
createElement(Badge, { text: '组件已调用' }),
createElement('badge', null, '小写HTML标签')
)
);
const case1 = {
direct_children_count: rulesRoot.children.length,
h1_class: rulesRoot.querySelector('h1').getAttribute('class'),
label_for: rulesRoot.querySelector('label').getAttribute('for'),
data_attr: rulesRoot.querySelector('p').getAttribute('data-myattribute'),
uppercase_rendered_tag: rulesRoot.querySelector('.badge').tagName,
lowercase_rendered_tag: rulesRoot.querySelector('badge').tagName,
comment_nodes: Array.from(rulesRoot.childNodes).filter(n => n.nodeType === Node.COMMENT_NODE).length
};
// Case 2: Expressions, ternary, short-circuit &&
const exprRoot = document.getElementById('expr-root');
const i = 1;
const countZero = 0;
const countThree = 3;
const isLoggedIn = true;
createRoot(exprRoot).render(
createElement(
'div', null,
createElement('p', { id: 'add' }, 1 + 1),
createElement('p', { id: 'prec' }, 2 + 3 * 5),
createElement('p', { id: 'tern-true' }, i === 1 ? 'True!' : 'False'),
createElement('p', { id: 'tern-false' }, (0 === 1) ? 'True!' : 'False'),
createElement('p', { id: 'login' }, isLoggedIn ? '欢迎回来,BlueSky!' : '请登录'),
countZero > 0 && createElement('p', { id: 'unread-zero' }, '不应渲染'),
countThree > 0 && createElement('p', { id: 'unread-three' }, '你有 ', countThree, ' 条未读消息')
)
);
const case2 = {
add_result: exprRoot.querySelector('#add').textContent,
precedence_result: exprRoot.querySelector('#prec').textContent,
ternary_true: exprRoot.querySelector('#tern-true').textContent,
ternary_false: exprRoot.querySelector('#tern-false').textContent,
login_msg: exprRoot.querySelector('#login').textContent,
zero_rendered: exprRoot.querySelector('#unread-zero') !== null,
three_msg: exprRoot.querySelector('#unread-three').textContent
};
// Case 3: Inline camelCase style auto-px + unitless + CSS Modules hashed class
const styleRoot = document.getElementById('style-root');
const myStyle = { fontSize: 100, color: '#FF0000', borderRadius: 8, opacity: 0.5 };
const styles = { container: 'Card_container__9f2a', title: 'Card_title__4c1b' };
createRoot(styleRoot).render(
createElement(
'div', { className: styles.container },
createElement('h1', { id: 'styled-h1', style: myStyle }, '内联样式标题'),
createElement('h3', { id: 'mod-h3', className: styles.title }, 'CSS Modules 标题')
)
);
const h1cs = getComputedStyle(styleRoot.querySelector('#styled-h1'));
const cardCs = getComputedStyle(styleRoot.querySelector('.' + styles.container));
const case3 = {
font_size: h1cs.fontSize,
color: h1cs.color,
border_radius: h1cs.borderRadius,
opacity: h1cs.opacity,
module_card_width: cardCs.width,
module_class_applied: styleRoot.querySelector('#mod-h3').className
};
// Case 4: Array auto-expansion & map() list with stable keys
const arrayRoot = document.getElementById('array-root');
const arr = [
createElement('h1', null, '数组标题一'),
createElement('h2', null, '数组标题二')
];
const items = [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
];
const listVNodes = items.map(item => createElement('li', { key: item.id, 'data-key': item.id }, item.name));
createRoot(arrayRoot).render(
createElement(
'div', null,
createElement('section', { id: 'arr-box' }, arr),
createElement('ul', { id: 'fruit-list' }, listVNodes)
)
);
const case4 = {
expanded_tags: Array.from(arrayRoot.querySelector('#arr-box').children).map(n => n.tagName),
list_texts: Array.from(arrayRoot.querySelectorAll('#fruit-list li')).map(n => n.textContent),
list_keys: listVNodes.map(v => v.key)
};
// Case 5: Standalone compiled JSX module mounting to root
const sepRoot = document.getElementById('sep-root');
const compiledElement = createElement('h1', { className: 'foo' }, 'Hello, world');
createRoot(sepRoot).render(compiledElement);
const case5 = {
tag: sepRoot.firstElementChild.tagName,
class_name: sepRoot.firstElementChild.className,
text: sepRoot.firstElementChild.textContent
};
return { case1, case2, case3, case4, case5 };
};
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML)
out = page.evaluate("window.runLab()")
browser.close()
expected = {
"jsx_rules_and_attributes": {
"direct_children_count": 5,
"h1_class": "title",
"label_for": "email-input",
"data_attr": "somevalue",
"uppercase_rendered_tag": "SPAN",
"lowercase_rendered_tag": "BADGE",
"comment_nodes": 0,
},
"jsx_expressions_and_conditionals": {
"add_result": "2",
"precedence_result": "17",
"ternary_true": "True!",
"ternary_false": "False",
"login_msg": "欢迎回来,BlueSky!",
"zero_rendered": False,
"three_msg": "你有 3 条未读消息",
},
"jsx_inline_style_and_css_modules": {
"font_size": "100px",
"color": "rgb(255, 0, 0)",
"border_radius": "8px",
"opacity": "0.5",
"module_card_width": "300px",
"module_class_applied": "Card_title__4c1b",
},
"jsx_array_expansion_and_list_keys": {
"expanded_tags": ["H1", "H2"],
"list_texts": ["苹果", "香蕉", "橙子"],
"list_keys": ["1", "2", "3"],
},
"jsx_separate_file_compile_equiv": {
"tag": "H1",
"class_name": "foo",
"text": "Hello, world",
},
}
actuals = {
"jsx_rules_and_attributes": out["case1"],
"jsx_expressions_and_conditionals": out["case2"],
"jsx_inline_style_and_css_modules": out["case3"],
"jsx_array_expansion_and_list_keys": out["case4"],
"jsx_separate_file_compile_equiv": out["case5"],
}
cases = [
{"name": name, "expected": expected[name], "actual": actuals[name], "passed": actuals[name] == expected[name]}
for name in expected
]
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 Fragment/className/htmlFor/data-* 与大小写标签区别、算术与条件分支结果、getComputedStyle 自动 px 与哈希类名、数组展开及独立模块挂载。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:8d2c128fa76cd1f56815a0d36e769335edc15e73ef035a4c1e1dd61dba5d65f3
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:a9a67e5e5360dcab8381462f35b33762ab8351cc4fce67207b099c6926f4354e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 JSX 中必须使用 `className` 和 `htmlFor`,且给 `style={{ fontSize: 100, opacity: 0.5 }}` 传数字时两者的计算结果有何不同?
展开参考解答
因为 JSX 本质是 JavaScript 语法扩展,`class` 与 `for` 是 JS 保留字,故改为 DOM 属性名 `className` 与 `htmlFor`;内联样式中 React 会为长度类数字属性自动补齐 `px`(`100px`),而对 `opacity`、`zIndex` 等无单位 CSS 属性保持原数值(`0.5`)。