"""Offline Chromium lab for React Ch 19: component-api."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>React Component API Lab</title></head>
<body>
<div id="lifecycle-root"></div>
<div id="counter-root"></div>
<div id="form-root"></div>
<div id="force-root"></div>
<script>
'use strict';
function createElement(type, props, ...children) {
const flat = children.flat(Infinity).filter(c => c !== null && c !== undefined && c !== false);
return { type, props: Object.assign({}, props || {}, { children: flat }) };
}
function renderVNode(vnode) {
if (typeof vnode === 'string' || typeof vnode === 'number') return document.createTextNode(String(vnode));
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 === 'value') el.value = String(v);
else if (k.startsWith('on') && typeof v === 'function') {
const ev = k === 'onChange' ? 'input' : k.slice(2).toLowerCase();
el.addEventListener(ev, 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 = {};
this._queue = [];
this._callbacks = [];
this._batching = false;
this._container = null;
}
setState(nextState, callback) {
this._queue.push(nextState);
if (typeof callback === 'function') this._callbacks.push(callback);
if (!this._batching) this._flush(false);
}
forceUpdate(callback) {
if (typeof callback === 'function') this._callbacks.push(callback);
this._flush(true);
}
_derive(props, state) {
const Ctor = this.constructor;
if (typeof Ctor.getDerivedStateFromProps === 'function') {
const derived = Ctor.getDerivedStateFromProps(props, state);
if (derived) return Object.assign({}, state, derived);
}
return state;
}
_mount(container) {
this._container = container;
this.state = this._derive(this.props, this.state);
this._commitDom();
if (typeof this.componentDidMount === 'function') this.componentDidMount();
}
_receiveProps(nextProps) {
this._runUpdate(nextProps, this.state, false);
}
_flush(isForce) {
let nextState = Object.assign({}, this.state);
for (const item of this._queue.splice(0)) {
const partial = typeof item === 'function' ? item(nextState, this.props) : item;
if (partial) nextState = Object.assign({}, nextState, partial);
}
this._runUpdate(this.props, nextState, isForce);
}
_runUpdate(nextProps, nextState, isForce) {
const derivedState = this._derive(nextProps, nextState);
const shouldRender = isForce || typeof this.shouldComponentUpdate !== 'function'
? true
: Boolean(this.shouldComponentUpdate(nextProps, derivedState));
const prevProps = this.props;
const prevState = this.state;
this.props = nextProps;
this.state = derivedState;
if (shouldRender) {
const vnode = this.render();
const snapshot = typeof this.getSnapshotBeforeUpdate === 'function'
? this.getSnapshotBeforeUpdate(prevProps, prevState)
: null;
this._commitDom(vnode);
if (typeof this.componentDidUpdate === 'function') {
this.componentDidUpdate(prevProps, prevState, snapshot);
}
}
for (const cb of this._callbacks.splice(0)) cb.call(this);
}
_commitDom(vnode) {
if (!this._container) return;
const tree = vnode !== undefined ? vnode : this.render();
this._container.innerHTML = '';
this._container.appendChild(renderVNode(tree));
}
_unmount() {
if (typeof this.componentWillUnmount === 'function') this.componentWillUnmount();
if (this._container) this._container.innerHTML = '';
this._container = null;
}
}
window.runLab = function () {
// Case 1: Full Component API lifecycle (getDerivedStateFromProps, SCU, getSnapshotBeforeUpdate, didUpdate, unmount)
const log = [];
class ApiLifecycleComp extends Component {
constructor(props) {
super(props);
this.state = { count: props.initial || 0 };
log.push('constructor');
}
static getDerivedStateFromProps(nextProps, prevState) {
log.push('getDerivedStateFromProps');
if (nextProps.reset) return { count: 0 };
return null;
}
componentDidMount() { log.push('componentDidMount'); }
shouldComponentUpdate(nextProps, nextState) {
const changed = nextState.count !== this.state.count;
log.push('shouldComponentUpdate:' + changed);
return changed;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
log.push('getSnapshotBeforeUpdate');
return { prevCount: prevState.count, scrollPosition: 120 };
}
componentDidUpdate(prevProps, prevState, snapshot) {
log.push(`componentDidUpdate:snap=${snapshot.prevCount}@${snapshot.scrollPosition}`);
}
componentWillUnmount() { log.push('componentWillUnmount'); }
render() {
log.push('render:' + this.state.count);
return createElement('div', { id: 'api-count' }, String(this.state.count));
}
}
const lc = new ApiLifecycleComp({ initial: 2, reset: false });
lc._mount(document.getElementById('lifecycle-root'));
lc.setState({ count: 2 }); // unchanged -> SCU returns false -> skips render
lc.setState({ count: 5 }); // changed -> renders + snapshot + didUpdate
lc._receiveProps({ initial: 2, reset: true }); // derived state resets count to 0
const countAfterReset = document.getElementById('api-count').textContent;
lc._unmount();
const case1 = { log, count_after_reset: countAfterReset };
// Case 2: setState shallow merge, optional post-commit callback, and clickable h2 Counter
const cbObserved = [];
class Counter extends Component {
constructor(props) {
super(props);
this.state = { clickCount: 0, keepTag: 'stable' };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(
state => ({ clickCount: state.clickCount + 1 }),
() => cbObserved.push({
stateCount: this.state.clickCount,
keepTag: this.state.keepTag,
domText: document.getElementById('counter-h2').textContent
})
);
}
render() {
return createElement('h2', { id: 'counter-h2', onClick: this.handleClick },
'点我!点击次数为: ', this.state.clickCount);
}
}
const counter = new Counter({});
counter._mount(document.getElementById('counter-root'));
document.getElementById('counter-h2').click();
document.getElementById('counter-h2').click();
const case2 = {
final_text: document.getElementById('counter-h2').textContent,
callback_observations: cbObserved
};
// Case 3: Controlled form component + conditional visibility + list rendering
let submittedVal = null;
class ControlledPanel extends Component {
constructor(props) {
super(props);
this.state = { value: '', isVisible: true };
}
handleChange = (e) => { this.setState({ value: e.target.value }); };
handleSubmit = (e) => { e.preventDefault(); submittedVal = this.state.value; };
toggleVisibility = () => { this.setState(prev => ({ isVisible: !prev.isVisible })); };
render() {
const items = ['Item 1', 'Item 2', 'Item 3'];
return createElement(
'div', null,
this.state.isVisible && createElement('p', { id: 'vis-p' }, 'This is visible'),
createElement('button', { id: 'vis-btn', onClick: this.toggleVisibility }, 'Toggle'),
createElement('ul', { id: 'api-list' }, items.map((it, i) => createElement('li', { key: i }, it))),
createElement('form', { id: 'ctrl-form', onSubmit: this.handleSubmit },
createElement('input', { id: 'ctrl-input', type: 'text', value: this.state.value, onChange: this.handleChange }),
createElement('button', { id: 'ctrl-submit', type: 'submit' }, 'Submit')
)
);
}
}
const panel = new ControlledPanel({});
panel._mount(document.getElementById('form-root'));
const inputEl = document.getElementById('ctrl-input');
inputEl.value = 'React API';
inputEl.dispatchEvent(new Event('input', { bubbles: true }));
document.getElementById('ctrl-form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
const visibleBefore = document.getElementById('vis-p') !== null;
document.getElementById('vis-btn').click();
const visibleAfter = document.getElementById('vis-p') !== null;
const listTexts = Array.from(document.querySelectorAll('#api-list li')).map(n => n.textContent);
const case3 = {
submitted_value: submittedVal,
visible_before: visibleBefore,
visible_after: visibleAfter,
list_texts: listTexts
};
// Case 4: forceUpdate bypasses shouldComponentUpdate(false) + legacy API status in React 18/19
let renderCount = 0;
class ForceDemo extends Component {
constructor(props) { super(props); this.externalVal = 'v1'; }
shouldComponentUpdate() { return false; }
render() {
renderCount += 1;
return createElement('span', { id: 'force-span' }, this.externalVal);
}
}
const fd = new ForceDemo({});
fd._mount(document.getElementById('force-root'));
fd.setState({ dummy: 1 }); // blocked by SCU
const countAfterBlockedSetState = renderCount;
fd.externalVal = 'v2';
fd.forceUpdate(); // bypasses SCU
const case4 = {
renders_after_blocked_setstate: countAfterBlockedSetState,
renders_after_force_update: renderCount,
dom_after_force_update: document.getElementById('force-span').textContent,
legacy_api_status: {
setState: 'supported_in_class_components',
forceUpdate: 'supported_but_discouraged',
replaceState: 'removed_since_react_16',
findDOMNode: 'deprecated_in_18_removed_in_19_use_ref'
}
};
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 = {
"lifecycle_and_derived_snapshot_api": {
"log": [
"constructor",
"getDerivedStateFromProps",
"render:2",
"componentDidMount",
"getDerivedStateFromProps",
"shouldComponentUpdate:false",
"getDerivedStateFromProps",
"shouldComponentUpdate:true",
"render:5",
"getSnapshotBeforeUpdate",
"componentDidUpdate:snap=2@120",
"getDerivedStateFromProps",
"shouldComponentUpdate:true",
"render:0",
"getSnapshotBeforeUpdate",
"componentDidUpdate:snap=5@120",
"componentWillUnmount",
],
"count_after_reset": "0",
},
"setstate_merge_batch_and_callback": {
"final_text": "点我!点击次数为: 2",
"callback_observations": [
{"stateCount": 1, "keepTag": "stable", "domText": "点我!点击次数为: 1"},
{"stateCount": 2, "keepTag": "stable", "domText": "点我!点击次数为: 2"},
],
},
"controlled_form_and_conditional_list": {
"submitted_value": "React API",
"visible_before": True,
"visible_after": False,
"list_texts": ["Item 1", "Item 2", "Item 3"],
},
"legacy_api_status_vs_react18_19": {
"renders_after_blocked_setstate": 1,
"renders_after_force_update": 2,
"dom_after_force_update": "v2",
"legacy_api_status": {
"setState": "supported_in_class_components",
"forceUpdate": "supported_but_discouraged",
"replaceState": "removed_since_react_16",
"findDOMNode": "deprecated_in_18_removed_in_19_use_ref",
},
},
}
actuals = {
"lifecycle_and_derived_snapshot_api": out["case1"],
"setstate_merge_batch_and_callback": out["case2"],
"controlled_form_and_conditional_list": out["case3"],
"legacy_api_status_vs_react18_19": 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-component-api-lab/explore-component-api.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-component-api.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3163.zip
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip