forwardRef

转发 ref 到子组件 - 实现 ref 穿透的高阶组件

核心概述

forwardRef 让组件可以将 ref 转发到其子组件。这在以下场景中非常有用:

  • 重用组件库逻辑 (如 Input, Button)
  • 需要暴露内部 DOM 节点的组件
  • 高阶组件 (HOC) 中转发 ref
  • 创建可复用的 UI 组件库

技术规格

TypeScript
function forwardRef<T, P>(
  render: (props: P, ref: Ref<T>) => ReactNode
): ReactForwardedRefComponent<T, P>
TypeScript
const MyInput = forwardRef((props, ref) => {
  return <input ref={ref} {...props} />;
});

// 使用
const inputRef = useRef(null);
<MyInput ref={inputRef} />

延伸阅读

这篇文章有帮助吗?