"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/react-jsx-lab/explore-jsx.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-jsx.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3177.zip
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip