蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在无头 Chromium 中离线验证 createRef 聚焦与样式改写、回调 Ref 生命周期、受控子句柄及 useRef 跨渲染状态

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-refs.py
explore-refs.py192 行
"""Offline Playwright Chromium verification for React Ch23 (refs)."""
import json
from playwright.sync_api import sync_playwright


def launch_browser(p):
    for kwargs in (
        dict(headless=True),
        dict(headless=True, channel="chrome"),
        dict(headless=True, channel="msedge"),
    ):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def case_create_ref_focus_and_dom_style(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <input id="my-input" type="text" />
  <button id="focus-btn">获取焦点</button>
  <button id="bg-btn">修改背景色</button>
  <script>
    function createRef() { return { current: null }; }
    const myInputRef = createRef();
    // Bind ref on mount
    myInputRef.current = document.getElementById('my-input');
    document.getElementById('focus-btn').addEventListener('click', () => {
      myInputRef.current.focus();
    });
    document.getElementById('bg-btn').addEventListener('click', () => {
      myInputRef.current.style.backgroundColor = 'yellow';
    });
  </script>
</body></html>"""
    page.set_content(html)
    page.click("#focus-btn")
    focused_id = page.evaluate("document.activeElement && document.activeElement.id")
    page.click("#bg-btn")
    bg_color = page.evaluate("getComputedStyle(document.getElementById('my-input')).backgroundColor")
    actual = {"focusedId": focused_id, "bgColor": bg_color}
    expected = {"focusedId": "my-input", "bgColor": "rgb(255, 255, 0)"}
    return dict(name="create_ref_focus_and_dom_style", expected=expected, actual=actual, passed=(actual == expected))


def case_callback_ref_mount_and_cleanup(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="host"></div>
  <script>
    const calls = [];
    let domNode = null;
    const setMyRef = (el) => {
      domNode = el;
      calls.push(el ? el.tagName : null);
    };
    const host = document.getElementById('host');
    const inp = document.createElement('input');
    inp.id = 'cb-input';
    host.appendChild(inp);
    setMyRef(inp);
    if (domNode) domNode.focus();
    const focusedOnMount = document.activeElement === inp;
    // Unmount
    host.removeChild(inp);
    setMyRef(null);
    window.__res = { calls, focusedOnMount, nodeAfterUnmount: domNode };
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__res")
    expected = {"calls": ["INPUT", None], "focusedOnMount": True, "nodeAfterUnmount": None}
    return dict(name="callback_ref_mount_and_cleanup", expected=expected, actual=actual, passed=(actual == expected))


def case_child_instance_and_imperative_handle(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <input id="child-input" type="text" value="子组件文本" />
  <button id="parent-focus">Focus Child Input</button>
  <script>
    // Class child instance ref + forwardRef/useImperativeHandle restricted API
    const childInputEl = document.getElementById('child-input');
    const childRef = { current: null };
    // Simulate useImperativeHandle exposing only focus & readValue (not raw DOM)
    childRef.current = {
      focusInput() { childInputEl.focus(); },
      readValue() { return childInputEl.value; },
    };
    document.getElementById('parent-focus').addEventListener('click', () => {
      childRef.current.focusInput();
    });
    window.__exposedKeys = Object.keys(childRef.current).sort();
    window.__val = childRef.current.readValue();
  </script>
</body></html>"""
    page.set_content(html)
    page.click("#parent-focus")
    actual = page.evaluate("""({
      focusedId: document.activeElement && document.activeElement.id,
      exposedKeys: window.__exposedKeys,
      readValue: window.__val,
      exposesRawStyle: Boolean(window.__exposedKeys.includes('style')),
    })""")
    expected = {
        "focusedId": "child-input",
        "exposedKeys": ["focusInput", "readValue"],
        "readValue": "子组件文本",
        "exposesRawStyle": False,
    }
    return dict(name="child_instance_and_imperative_handle", expected=expected, actual=actual, passed=(actual == expected))


def case_useref_dom_focus_and_prev_value(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <input id="hook-input" type="text" />
  <button id="hook-focus">Focus Input</button>
  <button id="inc-btn">+1</button>
  <p id="summary"></p>
  <script>
    const inputRef = { current: document.getElementById('hook-input') };
    const prevCountRef = { current: null };
    const renderCountRef = { current: 0 };
    let count = 0;

    function render() {
      renderCountRef.current += 1;
      const prev = prevCountRef.current;
      document.getElementById('summary').textContent = `curr=${count},prev=${prev},renders=${renderCountRef.current}`;
      prevCountRef.current = count;
    }
    render();
    document.getElementById('hook-focus').addEventListener('click', () => {
      inputRef.current.focus();
    });
    document.getElementById('inc-btn').addEventListener('click', () => {
      count += 1;
      render();
    });
    // Mutating ref directly does not trigger render
    const silentRef = { current: 100 };
    silentRef.current = 200;
    window.__silent = silentRef.current;
    window.__rendersBeforeClick = renderCountRef.current;
  </script>
</body></html>"""
    page.set_content(html)
    page.click("#hook-focus")
    focused_id = page.evaluate("document.activeElement && document.activeElement.id")
    page.click("#inc-btn")
    page.click("#inc-btn")
    actual = page.evaluate("""({
      focusedId: %r,
      summary: document.getElementById('summary').textContent,
      silentRef: window.__silent,
      rendersBeforeClick: window.__rendersBeforeClick,
    })""" % focused_id)
    expected = {
        "focusedId": "hook-input",
        "summary": "curr=2,prev=1,renders=3",
        "silentRef": 200,
        "rendersBeforeClick": 1,
    }
    return dict(name="useref_dom_focus_and_prev_value", expected=expected, actual=actual, passed=(actual == expected))


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            cases = [
                case_create_ref_focus_and_dom_style(page),
                case_callback_ref_mount_and_cleanup(page),
                case_child_instance_and_imperative_handle(page),
                case_useref_dom_focus_and_prev_value(page),
            ]
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/react-refs-lab/explore-refs.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-refs.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:React

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3185.zip

下载课程关联工程包:React

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习