Ref forwarding 是 React 提供的透传 ref 机制,使父组件 ref 能直达子组件内部 DOM 节点;需用 React.forwardRef 包裹组件,并将 ref 显式绑定到目标元素,支持逐层透传与自定义 Hook 协同。

Ref forwarding 是 React 提供的一种“透传 ref”的机制,不是 JavaScript 原生特性,而是 React 的 API 设计模式。它让父组件能将 ref 直接“转发”给子组件内部的某个 DOM 节点或子组件,而不是停留在包装组件这一层。
为什么需要 ref forwarding?
常见场景:你封装了一个自定义按钮组件 MyButton,外面用 React.forwardRef 包一层,但希望父组件调用 ref.current.focus() 时,真正聚焦的是内部的 <button>,而不是 MyButton 这个函数组件本身(函数组件默认不支持 ref)。
没有 ref forwarding 时,ref 会“卡”在组件边界上,无法触达内部真实 DOM。
基本写法:React.forwardRef
用 React.forwardRef 包裹组件函数,它接收两个参数:props 和 ref,并把 ref 显式地绑定到目标元素上:
立即学习“Java免费学习笔记(深入)”;
const MyInput = React.forwardRef((props, ref) => (
<input ref={ref} {...props} />
));
// 使用
function App() {
const inputRef = useRef();
return <MyInput ref={inputRef} placeholder="点击聚焦" />;
}
- ref 不再是 props 里的一个普通字段,而是被单独抽出来作为第二个参数
- 必须显式把 ref 赋给某个可 ref 的节点(如
<input>、<div>或另一个用 forwardRef 包装的组件) - 不能在 class 组件或普通函数组件里直接解构
{ ref }—— 那样 ref 就丢失了
结合自定义 Hook 或复合逻辑使用
ref forwarding 可以和业务逻辑共存。比如你想在输入框获得焦点时自动选中文字:
const SelectableInput = React.forwardRef((props, ref) => {
const inputRef = useRef(null);
useEffect(() => {
if (ref) {
// 把传入的 ref 和本地 ref 同步(可选)
if (typeof ref === 'function') ref(inputRef.current);
else ref.current = inputRef.current;
}
}, [ref]);
const handleFocus = () => {
inputRef.current?.select();
};
return <input ref={inputRef} onFocus={handleFocus} {...props} />;
});
- 这里用本地
inputRef控制行为,同时把外部 ref “同步”过去,兼顾封装性与可控性 - 注意判断
ref类型:可能是对象({ current: ... })也可能是函数,安全写法需兼容
转发 ref 到另一个自定义组件
如果子组件本身也是用 forwardRef 写的,可以逐层透传:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="fancy" {...props} />
));
const Wrapper = React.forwardRef((props, ref) => (
<div className="wrapper">
<FancyButton ref={ref} {...props} />
</div>
));
- 只要中间每一层都用
forwardRef并把 ref 传下去,ref 就能直达最内层 DOM - 类似“管道”,不拦截、不消耗,只透传
基本上就这些。ref forwarding 不复杂但容易忽略,关键就两点:用 React.forwardRef 包组件,再把收到的 ref 绑定到该去的地方。











