蓝色天空.知识 · 实践 · 创造
我的收藏
React 教程目录 42章
React / LEARN BY DOING

React Refs

核对 React.createRef、回调 Ref、useRef Hook、直接操作 DOM、访问子组件实例与 useImperativeHandle/forwardRef 自定义暴露,并说明历史 getDOMNode() 迁移,辅以离线 Chromium 实测。

学完这一章,你能够

  • 核对 React.createRef、回调 Ref、useRef Hook、直接操作 DOM、访问子组件实例与 useImperativeHandle/forwardRef 自定义暴露,并说明历史 getDOMNode() 迁移,辅以离线 Chromium 实测。

Refs 定位、适用场景与创建方式

Ref 是 React 提供的特殊属性,可附加到 `render()` 输出的 DOM 元素或类组件上,用于在渲染周期外稳定拿到对应的底层支撑实例(backing instance)。Refs 适合命令式操作场景,例如管理输入框焦点、文本选区、媒体播放控制、触发强制动画或集成第三方 DOM 库。

现代 React 提供两类标准创建方式:类组件中在构造函数调用 `React.createRef()` 创建 `{ current: null }` 对象并赋给实例属性,在 `render` 中通过 `ref={this.myInputRef}` 绑定,随后在方法内经 `this.myInputRef.current` 访问目标节点(配合类字段箭头函数 `handleClick = () => {}` 可免去手动 `bind(this)`);函数组件则使用 `useRef` Hook。

在典型焦点控制示例中,点击按钮通过 `this.myInputRef.current.focus()` 让绑定输入框立即获得焦点。关于早期资料提及的 `getDOMNode()`:该方法属于 React 0.13 之前的历史接口,后由 `ReactDOM.findDOMNode` 替代,而在 React 19 中 `findDOMNode` 也已正式移除;现代工程应一律使用 `createRef` 或 `useRef` 获取真实 DOM 节点。

createRef、回调 Refs 与直接操作 DOM

使用 `React.createRef()` 既可在 `componentDidMount` 阶段自动聚焦输入框,也可在点击事件中直接改写 DOM 样式(如 `this.myRef.current.style.backgroundColor = 'yellow'`)。本站离线 Chromium 实测(`create_ref_focus_and_dom_style`):点击聚焦按钮后 `document.activeElement.id === 'my-input'`,点击变色按钮后计算背景色变为 `rgb(255, 255, 0)`。

另一种方式是回调 Refs(`ref={element => { this.myRef = element; }}`):React 会在节点挂载时传入真实 DOM 元素,并在卸载时传入 `null` 完成清理(React 19 进一步支持在回调 Ref 中直接返回清理函数)。虽在 React 16.3 引入 `createRef` 后常规场景更推荐对象 Ref,但动态列表测量等场景仍常用回调 Refs。本站实测(`callback_ref_mount_and_cleanup`):挂载与卸载回调序列准确记录为 `['INPUT', null]`,挂载即获焦且卸载后引用归 `null`。

子组件实例访问、useRef Hook 与最佳实践小结

将 Ref 绑定到类子组件(`<ChildComponent ref={this.childRef} />`)后,父组件可直接调用子实例公开方法(如 `this.childRef.current.focusInput()`)。而函数组件没有实例,传统上需借助 `forwardRef` 与 `useImperativeHandle`(React 19 起可直接把 `ref` 当普通 prop 接收)仅向父组件暴露受控方法集合,避免泄露完整 DOM 节点。本站实测(`child_instance_and_imperative_handle`):父按钮触发子句柄 `focusInput()` 成功聚焦 `#child-input`,暴露键集合严格限定为 `['focusInput', 'readValue']`(`exposesRawStyle === false`)。

函数组件中调用 `const inputRef = useRef(null)` 不仅可用于绑定 DOM 焦点,还能在多次渲染间持久化任意可变值(例如记录上一次渲染状态或渲染次数)且修改 `.current` 不会触发重渲染。总结 Refs 核心要点:类组件用 `React.createRef`、函数组件用 `useRef`;按需访问 DOM 或子组件实例;通过 `useImperativeHandle` + `forwardRef` 精细封装暴露接口;在并发渲染场景中 Ref 与 `useTransition` 协同正常。本站实测(`useref_dom_focus_and_prev_value`):点击按钮成功聚焦 `#hook-input`,修改静默 Ref 为 `200` 保持渲染次数仍为 `1`,两次递增后准确追踪 `curr=2,prev=1,renders=3`。

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

含完整源码 · 192 行
展开查看收起
python
"""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()
核对 createRef 聚焦与背景色 rgb(255,255,0)、回调 Ref ['INPUT', null] 挂载/卸载调用、useImperativeHandle 仅暴露指定方法,以及 useRef 修改不触发重渲染且精确追踪前值。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a3185.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:React

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

下载课程关联工程包:React

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

修改 useRef().current 会同步变更持久化对象但不会触发组件重新渲染,适合保存 DOM 引用或前次值;useState 更新则会调度重渲染。getDOMNode() 与随后的 findDOMNode 均已废弃并被移除,现代 React 统一通过 Ref 引用 DOM 节点。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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