React 条件渲染
核对 if 分支、元素变量、逻辑与 &&(含数字 0 渲染陷阱)、三目运算符以及组件返回 null 隐藏输出仍触发生命周期的离线 Chromium 实测。
学完这一章,你能够
- 核对 if 分支、元素变量、逻辑与 &&(含数字 0 渲染陷阱)、三目运算符以及组件返回 null 隐藏输出仍触发生命周期的离线 Chromium 实测。
if 条件分支与元素变量
React 中的条件渲染与普通 JavaScript 分支完全一致:将不同 UI 行为封装为独立组件(如 `UserGreeting` 与 `GuestGreeting`),再在父组件 `Greeting` 内通过 `if (isLoggedIn)` 决定返回哪一个元素,交由 React 更新界面。本站离线 Chromium 实测 `isLoggedIn=false` 输出 `请先注册。`,改为 `true` 输出 `欢迎回来!`。
当只需按状态切换组件输出中的局部片段而其余结构保持不变时,可以使用普通变量暂存待渲染元素(元素变量)。在有状态的 `LoginControl` 组件中,根据 `this.state.isLoggedIn` 将 `button` 变量赋值为 `<LogoutButton />` 或 `<LoginButton />`,再统一与 `<Greeting />` 一起返回。本站实测初始显示 `请先注册。` 与 `登录` 按钮,点击后切为 `欢迎回来!` 与 `退出` 按钮,再次点击准确还原。
逻辑与 && 短路与三目运算符
在 JSX 花括号中可利用 JavaScript 逻辑与 `&&` 简写“满足条件才渲染”的分支:`true && element` 返回右侧元素,`false && element` 返回 `false` 并被 React 忽略。实战中务必避免左侧直接写数字 `0`(例如 `unreadMessages.length && <h2 />` 会在长度为 0 时把字面量 `0` 渲染到页面上),应始终写成布尔表达式 `unreadMessages.length > 0 && ...`。本站实测 3 条未读时渲染 `您有 3 条未读信息。`,空数组时 `<h2>` 不存在,而对照组 `length && ...` 确实渲染出了字符 `"0"`。
需要在两种输出之间二选一时,可在 JSX 中内联条件(三目)运算符 `condition ? exprA : exprB`。它既适合切换短文本片段(如 `The user is currently/not logged in.`),也可用于切换两段较大组件树;若分支逻辑过长、嵌套层级过深,则建议提取为独立子组件或元素变量以维持可读性。本站实测三目分支精准输出 `currently` 与 `not` 两种句子。
返回 null 阻止组件渲染与生命周期行为
若希望组件在特定条件下不向 DOM 输出任何内容,只需让函数组件或类组件 `render()` 直接返回 `null`(如 `WarningBanner` 在 `!props.warn` 时返回 `null`)。需要重点掌握的是:返回 `null` 仅隐藏自身 DOM 渲染结果,并不会中断该组件已挂载实例的生命周期回调——`componentDidUpdate`(以及旧版 `UNSAFE_componentWillUpdate`)仍会照常触发。本站实测 `Page` 点击按钮切换 `showWarning`(`隐藏` ↔ `显示`)时,`.warning` 横幅随之显隐,且 `WarningBanner` 的生命周期日志连续记录 `didUpdate:true->false` 与 `didUpdate:false->true`。
离线 Chromium 验证 if/元素变量、&& 数字 0 陷阱、三目分支与返回 null 生命周期
"""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()
- 核对 Greeting 登录态切换、LoginControl 点击登录/退出、Mailbox 3 条与 0 条消息及数字 0 陷阱、三目文本切换,以及 WarningBanner 返回 null 后 componentDidUpdate 仍按序触发。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a36f0aecacee190d75e93851045953bb65b5a5594475c30b2aaccbda58e2b3c4
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:0c172439a804f863ffb0bcd6b9e04c3901e34803b7d34064ca062ac31d17ab04
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 JSX 中写 `{items.length && <List />}` 存在什么隐患?当类组件 `render()` 返回 `null` 时其 `componentDidUpdate` 还会执行吗?
展开参考解答
当 `items.length` 为 `0` 时,JavaScript 短路返回数字 `0`,React 会将数字 `0` 作为文本渲染到页面,应改写为 `{items.length > 0 && <List />}`;组件返回 `null` 仅阻止 DOM 输出,实例并未卸载,`componentDidUpdate` 等更新生命周期仍会正常调用。