"""Offline Chromium lab for React Ch 17: conditional-rendering."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>React Conditional Rendering Lab</title></head>
<body>
<div id="if-root"></div>
<div id="ctrl-root"></div>
<div id="expr-root"></div>
<div id="null-root"></div>
<script>
'use strict';
function createElement(type, props, ...children) {
const flat = [];
(function collect(list) {
for (const item of list) {
if (Array.isArray(item)) collect(item);
else if (item !== null && item !== undefined && typeof item !== 'boolean') flat.push(item);
}
})(children);
return { type, props: Object.assign({}, props || {}, { children: flat }) };
}
function renderVNode(vnode) {
if (vnode === null || vnode === undefined || typeof vnode === 'boolean') return document.createTextNode('');
if (typeof vnode === 'string' || typeof vnode === 'number') return document.createTextNode(String(vnode));
if (typeof vnode.type === 'function') {
return renderVNode(vnode.type(vnode.props));
}
const el = document.createElement(vnode.type);
for (const [k, v] of Object.entries(vnode.props)) {
if (k === 'children' || v === undefined || v === null) continue;
if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2).toLowerCase(), v);
else el.setAttribute(k === 'className' ? 'class' : k, String(v));
}
vnode.props.children.forEach(c => el.appendChild(renderVNode(c)));
return el;
}
class Component {
constructor(props) { this.props = props; this.state = {}; }
setState(updater) {
const next = typeof updater === 'function' ? updater(this.state, this.props) : updater;
this.state = Object.assign({}, this.state, next);
this._commit();
}
_commit() {
if (!this._container) return;
this._container.innerHTML = '';
this._container.appendChild(renderVNode(this.render()));
}
_mount(container) {
this._container = container;
this._commit();
}
}
window.runLab = function () {
// Case 1: if branching between UserGreeting & GuestGreeting
function UserGreeting() { return createElement('h1', null, '欢迎回来!'); }
function GuestGreeting() { return createElement('h1', null, '请先注册。'); }
function Greeting({ isLoggedIn }) {
if (isLoggedIn) return createElement(UserGreeting, null);
return createElement(GuestGreeting, null);
}
const ifRoot = document.getElementById('if-root');
ifRoot.appendChild(renderVNode(createElement(Greeting, { isLoggedIn: false })));
const guestText = ifRoot.textContent;
ifRoot.innerHTML = '';
ifRoot.appendChild(renderVNode(createElement(Greeting, { isLoggedIn: true })));
const userText = ifRoot.textContent;
const case1 = { guest_text: guestText, user_text: userText };
// Case 2: Element variable inside stateful LoginControl
function LoginButton(props) { return createElement('button', { id: 'auth-btn', onClick: props.onClick }, '登录'); }
function LogoutButton(props) { return createElement('button', { id: 'auth-btn', onClick: props.onClick }, '退出'); }
class LoginControl extends Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = { isLoggedIn: false };
}
handleLoginClick() { this.setState({ isLoggedIn: true }); }
handleLogoutClick() { this.setState({ isLoggedIn: false }); }
render() {
const isLoggedIn = this.state.isLoggedIn;
let button = null;
if (isLoggedIn) {
button = createElement(LogoutButton, { onClick: this.handleLogoutClick });
} else {
button = createElement(LoginButton, { onClick: this.handleLoginClick });
}
return createElement('div', null, createElement(Greeting, { isLoggedIn }), button);
}
}
const ctrlRoot = document.getElementById('ctrl-root');
const ctrl = new LoginControl({});
ctrl._mount(ctrlRoot);
const step0 = { heading: ctrlRoot.querySelector('h1').textContent, button: ctrlRoot.querySelector('#auth-btn').textContent };
ctrlRoot.querySelector('#auth-btn').click();
const step1 = { heading: ctrlRoot.querySelector('h1').textContent, button: ctrlRoot.querySelector('#auth-btn').textContent };
ctrlRoot.querySelector('#auth-btn').click();
const step2 = { heading: ctrlRoot.querySelector('h1').textContent, button: ctrlRoot.querySelector('#auth-btn').textContent };
const case2 = { initial: step0, after_login: step1, after_logout: step2 };
// Case 3: Logical && (including numeric 0 pitfall) + ternary operator
function Mailbox({ unreadMessages }) {
return createElement(
'div', null,
createElement('h1', null, 'Hello!'),
unreadMessages.length > 0 && createElement('h2', { className: 'unread' }, '您有 ', unreadMessages.length, ' 条未读信息。'),
createElement('span', { className: 'zero-pitfall' }, unreadMessages.length && createElement('em', null, 'non-empty'))
);
}
const exprRoot = document.getElementById('expr-root');
exprRoot.appendChild(renderVNode(createElement(Mailbox, { unreadMessages: ['React', 'Re: React', 'Re:Re: React'] })));
const withThree = exprRoot.querySelector('.unread').textContent;
exprRoot.innerHTML = '';
exprRoot.appendChild(renderVNode(createElement(Mailbox, { unreadMessages: [] })));
const withZeroHasH2 = exprRoot.querySelector('.unread') !== null;
const zeroPitfallText = exprRoot.querySelector('.zero-pitfall').textContent;
function StatusLine({ isLoggedIn }) {
return createElement('div', { className: 'status' }, 'The user is ', createElement('b', null, isLoggedIn ? 'currently' : 'not'), ' logged in.');
}
exprRoot.innerHTML = '';
exprRoot.appendChild(renderVNode(createElement(StatusLine, { isLoggedIn: true })));
const ternTrue = exprRoot.querySelector('.status').textContent;
exprRoot.innerHTML = '';
exprRoot.appendChild(renderVNode(createElement(StatusLine, { isLoggedIn: false })));
const ternFalse = exprRoot.querySelector('.status').textContent;
const case3 = {
with_three_unread: withThree,
with_zero_has_h2: withZeroHasH2,
zero_pitfall_renders_zero: zeroPitfallText,
ternary_true: ternTrue,
ternary_false: ternFalse
};
// Case 4: Returning null hides component DOM output while componentDidUpdate still runs
const bannerLifecycleLog = [];
class WarningBanner {
constructor(props) { this.props = props; }
update(nextProps) {
const prevProps = this.props;
this.props = nextProps;
const out = this.render();
this.componentDidUpdate(prevProps);
return out;
}
componentDidUpdate(prevProps) {
bannerLifecycleLog.push(`didUpdate:${prevProps.warn}->${this.props.warn}`);
}
render() {
if (!this.props.warn) return null;
return createElement('div', { className: 'warning' }, '警告!');
}
}
const nullRoot = document.getElementById('null-root');
const banner = new WarningBanner({ warn: true });
let showWarning = true;
function commitPage(isUpdate) {
const bannerVNode = isUpdate ? banner.update({ warn: showWarning }) : banner.render();
nullRoot.innerHTML = '';
const wrap = document.createElement('div');
if (bannerVNode !== null) wrap.appendChild(renderVNode(bannerVNode));
const btn = document.createElement('button');
btn.id = 'warn-toggle';
btn.textContent = showWarning ? '隐藏' : '显示';
btn.addEventListener('click', () => { showWarning = !showWarning; commitPage(true); });
wrap.appendChild(btn);
nullRoot.appendChild(wrap);
}
commitPage(false);
const s0 = { hasBanner: nullRoot.querySelector('.warning') !== null, btn: nullRoot.querySelector('#warn-toggle').textContent };
nullRoot.querySelector('#warn-toggle').click();
const s1 = { hasBanner: nullRoot.querySelector('.warning') !== null, btn: nullRoot.querySelector('#warn-toggle').textContent };
nullRoot.querySelector('#warn-toggle').click();
const s2 = { hasBanner: nullRoot.querySelector('.warning') !== null, btn: nullRoot.querySelector('#warn-toggle').textContent };
const case4 = {
initial: s0,
after_hide: s1,
after_show: s2,
banner_lifecycle_log: bannerLifecycleLog
};
return { case1, case2, case3, case4 };
};
</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 = {
"if_statement_greeting": {
"guest_text": "请先注册。",
"user_text": "欢迎回来!",
},
"element_variable_login_control": {
"initial": {"heading": "请先注册。", "button": "登录"},
"after_login": {"heading": "欢迎回来!", "button": "退出"},
"after_logout": {"heading": "请先注册。", "button": "登录"},
},
"logical_and_and_ternary": {
"with_three_unread": "您有 3 条未读信息。",
"with_zero_has_h2": False,
"zero_pitfall_renders_zero": "0",
"ternary_true": "The user is currently logged in.",
"ternary_false": "The user is not logged in.",
},
"returning_null_and_lifecycle": {
"initial": {"hasBanner": True, "btn": "隐藏"},
"after_hide": {"hasBanner": False, "btn": "显示"},
"after_show": {"hasBanner": True, "btn": "隐藏"},
"banner_lifecycle_log": ["didUpdate:true->false", "didUpdate:false->true"],
},
}
actuals = {
"if_statement_greeting": out["case1"],
"element_variable_login_control": out["case2"],
"logical_and_and_ternary": out["case3"],
"returning_null_and_lifecycle": out["case4"],
}
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-conditional-rendering-lab/explore-conditional-rendering.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-conditional-rendering.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3167.zip
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip