react18-string-refs

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React 18 String Refs Migration

React 18 字符串Ref迁移

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.
字符串ref(
ref="myInput"
+
this.refs.myInput
)在React 16.3版本中已被弃用,在React 18.3.1中会触发警告,且在React 19中已被完全移除

Quick Pattern Map

快速模式映射

PatternReference
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
模式参考资料
DOM元素上的单个ref→ patterns.md#single-ref
单个组件内的多个ref→ patterns.md#multiple-refs
列表中的ref / 动态ref→ patterns.md#list-refs
回调ref(替代方案)→ patterns.md#callback-refs
传递给子组件的Ref→ patterns.md#forwarded-refs

Scan Command

扫描命令

bash
undefined
bash
undefined

Find all string ref assignments in JSX

Find all string ref assignments in JSX

grep -rn 'ref="' src/ --include=".js" --include=".jsx" | grep -v ".test."
grep -rn 'ref="' src/ --include=".js" --include=".jsx" | grep -v ".test."

Find all this.refs accessors

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.
grep -rn "this.refs." src/ --include=".js" --include=".jsx" | grep -v ".test."

上述两项需要一同迁移:找到每个组件对应的`ref="name"`和`this.refs.name`访问语句,成对处理。

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.refName
    this.refName.current
    everywhere
Read
references/patterns.md
for the full before/after for each case.
所有字符串ref都需迁移为
React.createRef()
  1. 添加
    refName = React.createRef();
    作为类字段(或写在构造函数中)
  2. 将JSX中的
    ref="refName"
    替换为
    ref={this.refName}
  3. 将所有位置的
    this.refs.refName
    替换为
    this.refName.current
阅读
references/patterns.md
查看每种场景的完整前后对比示例。