You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中SVG函数组件无法获取Ref的问题解决求助

解决Next.js Link组件中使用自定义SVG函数组件的Ref错误

错误原因

Next.js的Link组件会尝试为直接子元素附加ref以优化导航行为,但你的Add是普通函数组件,默认不支持接收ref,因此触发报错:"Function components cannot be given refs. Attempts to access this ref will fail"。


解决方案

方案1:用React.forwardRef包装SVG组件

修改Add组件,通过forwardRef将ref传递给内部的<svg>原生元素,让Link可以正常获取ref:

import React, { forwardRef, ComponentProps } from 'react';

// 用forwardRef包装,将ref传递给内部svg标签
const Add = forwardRef<SVGSVGElement, ComponentProps>(({ width, height }, ref) => (
  <svg 
    ref={ref} 
    width={width} 
    height={height} 
    viewBox="0 0 40 38" 
    fill="none" 
    xmlns="http://www.w3.org/2000/svg"
  >
    <circle cx="10" cy="19.5" r="9.5" transform="rotate(-90 10 19.5)" fill="#F292B7" />
    <circle cx="20" cy="28.5" r="9.5" fill="#0066D9" />
    <circle cx="30" cy="19.5" r="9.5" transform="rotate(-90 30 19.5)" fill="#00AC62" />
    <circle cx="20" cy="9.5" r="9.5" fill="#0066D9" />
    <path
      fillRule="evenodd"
      clipRule="evenodd"
      d="M19.4863 18.9864C14.6486 18.7286 10.7714 14.8515 10.5136 10.0137C15.3514 10.2714 19.2286 14.1486 19.4863 18.9864Z"
      fill="#F292B7"
    />
    <rect x="19" y="11" width="3" height="16" rx="1.5" fill="white" />
    <rect x="12.5" y="20.5" width="3" height="16" rx="1.5" transform="rotate(-90 12.5 20.5)" fill="white" />
  </svg>
));

// 可选:设置组件显示名称,方便DevTools识别
Add.displayName = 'Add';

修改后保持原用法即可:

<Link href="/add">
  <Add width={40} height={40} />
</Link>

方案2:嵌套<a>标签(与现有代码风格统一)

参考前两个导航项的写法,将Add组件放在<a>标签内——原生<a>元素支持ref,Link会自动处理它,无需修改SVG组件:

<li>
  <Link href="/add">
    <a>
      <Add width={40} height={40} />
    </a>
  </Link>
</li>

方案选择

  • 若需要直接将SVG作为Link的子元素,选择方案1;
  • 若想保持代码风格一致,方案2更简单直接。

内容的提问来源于stack exchange,提问作者김정수

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:48:58