跳到正文
Skillpedia
网站与界面(前端)40k · #7388

react18-string-refs

它能做什么

这个工具可以帮你把旧版 React 代码更新到较新的写法。它会把文本形式的引用(比如 `ref='myInput'`)转换为更现代的格式(`React.createRef()`),确保你的代码能正常运行。

适用场景

  • ✓当你正在把一个旧的 React 项目升级到较新版本时。
  • ✓如果你的 React 代码中出现关于“字符串 refs”(string refs)的警告时。
  • ✓在你开始手动改写代码中的引用之前。

技能链接

https://github.com/github/awesome-copilot/blob/main/skills/react18-string-refs/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/github/awesome-copilot/blob/main/skills/react18-string-refs/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“我该如何把 React 中的“字符串 refs”更新为现代写法?”

每周 5 个新技能,1 分钟读完。

工作原理

这个工具会先找出你在 React 代码中使用文本引用的地方,然后展示具体的替换方式,把它们改为 `React.createRef()`。这是当前 React 版本中的正确做法。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

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.refName → this.refName.current everywhere

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

常见问题

什么是“字符串 refs”(string refs)?

这是 React 中一种旧的引用元素方式,通过文本名称来引用,比如 `ref='myInput'`。这种方式已经被更安全、更现代的方式取代了。

为什么需要更新?

“字符串 refs”已经被弃用,并将在未来的 React 版本中移除。及早更新可以确保你的代码继续正常运行,并兼容新版本。

什么是 `React.createRef()`?

它是在 React 类组件中创建元素引用的推荐现代方式,更安全,也更加明确。

详情

作者的原始描述

Provides exact migration patterns for React string refs (ref="name" + this.refs.name) to React.createRef() in class components. Use this skill whenever migrating string ref usage - including single element refs, multiple refs in a component, refs in lists, callback refs, and refs passed to child components. Always use this skill before writing any ref migration code - the multiple-refs-in-list pat

repo: github/awesome-copilot

热度

GitHub 星标
40k
排名
#7388
许可证
MIT
更新时间
2026/10/15

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能