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

React Router 4中使用ref无法聚焦Link组件的解决方案咨询

问题根源

直接给 <Link> 加 ref,拿到的是 Link 组件的实例,不是底层的 <a> DOM 元素,而组件实例没有 focus() 方法,所以调用会报错。
用 innerRef 时如果直接传 useRef 创建的对象,不符合 Link 组件对 innerRef 的类型要求(只接受函数或字符串),因此会抛出警告。

可行解决方案

方案一:使用回调式 innerRef(推荐)

把 innerRef 设为一个回调函数,将底层 DOM 元素赋值给你的 ref 对象。这样既符合 prop 类型要求,又能拿到真正的 DOM 节点调用 focus():

const TestComponent = () => {
  const linkRef = React.useRef(null);

  const testFunction = () => {
    linkRef.current?.focus();
  };

  return (
    <div>
      <button onClick={testFunction}>Focus button here</button>
      <Link 
        to="/testUrl.com" 
        innerRef={(el) => linkRef.current = el} 
      >
        Test Here
      </Link>
    </div>
  );
};

方案二:从组件实例获取 DOM 元素(不推荐)

如果不想用 innerRef,可以从 Link 组件实例中找到它渲染的 <a> 标签,但这种方式依赖 Link 的内部渲染结构,后续 React Router 更新可能失效:

const TestComponent = () => {
  const linkRef = React.useRef(null);

  const testFunction = () => {
    const domLink = linkRef.current?.querySelector('a');
    domLink?.focus();
  };

  return (
    <div>
      <button onClick={testFunction}>Focus button here</button>
      <Link ref={linkRef} to="/testUrl.com">Test Here</Link>
    </div>
  );
};

内容的提问来源于stack exchange,提问作者Dog

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:30:05