技能 编程开发 React 字符串引用迁移指南

React 字符串引用迁移指南

v20260410
react18-string-refs
本技能提供了一份详尽的指南,用于帮助开发者将React中已废弃的字符串引用(String Refs)迁移到推荐的`React.createRef()`模式。随着React 19的发布,字符串引用已被移除。本指南详细覆盖了所有类型的引用迁移场景,包括单元素引用、列表引用和回调引用,确保代码能够兼容React 18及更高版本。
获取技能
450 次下载
概览

React 18 String Refs Migration

String refs (ref="myInput" + this.refs.myInput) were deprecated in React 16.3, warn in React 18.3.1, and are removed in React 19.

Quick Pattern Map

Pattern Reference
Single ref on a DOM element → patterns.md#single-ref
Multiple refs in one component → patterns.md#multiple-refs
Refs in a list / dynamic refs → patterns.md#list-refs
Callback refs (alternative approach) → patterns.md#callback-refs
Ref passed to a child component → patterns.md#forwarded-refs

Scan Command

# Find all string ref assignments in JSX
grep -rn 'ref="' src/ --include="*.js" --include="*.jsx" | grep -v "\.test\."

# Find all this.refs accessors
grep -rn "this\.refs\." src/ --include="*.js" --include="*.jsx" | grep -v "\.test\."

Both should be migrated together - find the ref="name" and the this.refs.name accesses for each component as a pair.

The Migration Rule

Every string ref migrates to React.createRef():

  1. Add refName = React.createRef(); as a class field (or in constructor)
  2. Replace ref="refName"ref={this.refName} in JSX
  3. Replace this.refs.refNamethis.refName.current everywhere

Read references/patterns.md for the full before/after for each case.

信息
Category 编程开发
Name react18-string-refs
版本 v20260410
大小 3KB
更新时间 2026-04-12
语言