关于 react18-string-refs
面向 React 开发者的迁移技能,用于在 React 19 移除字符串 ref 前替换旧写法。它提供扫描方法,并覆盖常见 ref 用法的改写模式。
主要功能
- 01扫描 JSX 赋值和 this.refs 访问
- 02用 React.createRef() 替换字符串 ref
- 03处理单个和多个 ref
- 04涵盖列表、回调及转发 ref
适用场景
- 01定位 React 代码库中的字符串 ref
- 02为 React 19 升级改写组件
- 03为动态 ref 或子组件 ref 选择模式
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ github/ awesome-copilot --skill react18-string-refs安装后在 Claude Code 中输入/react18-string-refs确认已加载。
附带文件references/patterns.md
详细介绍
React 18 字符串 Ref 迁移
字符串 ref(ref="myInput" + this.refs.myInput)在 React 16.3 中已被弃用,在 React 18.3.1 中会发出警告,并在 React 19 中被移除。
快速模式对照表
| 模式 | 参考 |
|---|---|
| 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 |
扫描命令
# 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\."
两者应一起迁移 - 将每个组件的 ref="name" 和 this.refs.name 访问作为一对来查找。
迁移规则
每个字符串 ref 都迁移到 React.createRef():
- 添加
refName = React.createRef();作为类字段(或在构造函数中) - 在 JSX 中将
ref="refName"→ref={this.refName} - 在所有地方将
this.refs.refName→this.refName.current
阅读 references/patterns.md 了解每种情况的完整前后对比。
评论
支持 Markdown