forwardRef是什么
forwardRef 让父组件能把 ref 穿透传递给子组件内部的 DOM 元素。
普通函数组件不接收 ref 参数:
// ❌ 父组件传的 ref 拿不到 <svg>
function Icon(props) {
return <svg {...props} />;
}
<Icon ref={svgRef} />; // ref 无效,React 会警告
用 forwardRef 后:
// ✅ ref 直接传到 <svg> 上
const Icon = forwardRef<SVGSVGElement>((props, ref) => {
return <svg ref={ref} {...props} />;
});
<Icon ref={svgRef} />; // svgRef.current === 真实的 SVG DOM 元素
在我们的场景里用它,主要是因为 LucideIcon 的类型定义是 ForwardRefExoticComponent——lucide 的所有图标都是用 forwardRef 包的。addIcons 要求传入符合这个类型的组件,所以 GithubIcon 也必须用 forwardRef 才能类型匹配。
不过在 React 19 里,forwardRef 已经不再需要了——ref 变成了普通 prop,可以直接传递:
// React 19 写法,不需要 forwardRef
function Icon({ ref, ...props }: React.SVGProps<SVGSVGElement> & { ref?: React.Ref<SVGSVGElement> }) {
return <svg ref={ref} {...props} />;
}
但 lucide 的类型定义还是基于 forwardRef 的,所以我们要和它的类型匹配还是得用 forwardRef。
