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

使用React Router Dom 6.4的NavLink跳转外部链接时本地路径被追加的问题

解决React Router Dom 6.4中HashRouter下外部链接被追加本地路径的问题

问题原因

NavLink是React Router专为应用内部路由跳转设计的组件,它会将to属性的值视为相对路径,结合当前HashRouter的路由上下文(即/#/前缀)拼接成最终路径。当你传入完整的外部URL时,它不会识别为外部地址,而是当作内部路径的一部分,导致外部URL被追加到本地主机路径之后,出现localhost:3000/#/http://www.saveur.com/article/Recipes/这种错误结果。

解决方案

处理外部链接时,直接使用原生<a>标签替代NavLink,这是浏览器处理外部跳转的标准方式:

<div className='recipe-intro'>
    <p className='cus-type'>{ Capitalize(recipieInfo.recipe.cuisineType[0])}</p>
    <a 
     target='_blank' 
     href={recipieInfo.recipe.url} 
     className="item-link"
     rel="noopener noreferrer">
       {recipieInfo.recipe.label}
    </a> 
    <NutriInfo recipieInfo={recipieInfo} />              
</div>

注意:添加rel="noopener noreferrer"是打开新窗口时的安全最佳实践,可防止新页面通过window.opener控制原页面。

进阶封装(可选)

如果需要在项目中同时处理内部、外部链接,可以封装一个通用组件自动区分:

import { NavLink } from 'react-router-dom';

const CustomLink = ({ to, children, ...props }) => {
  // 通过正则判断是否为外部链接
  const isExternal = /^https?:\/\//.test(to);
  
  if (isExternal) {
    return (
      <a 
        href={to} 
        target="_blank" 
        rel="noopener noreferrer" 
        {...props}>
        {children}
      </a>
    );
  }
  
  return <NavLink to={to} {...props}>{children}</NavLink>;
};

export default CustomLink;

使用时直接替换原NavLink即可:

<CustomLink 
  target='_blank' 
  to={recipieInfo.recipe.url} 
  className="item-link">
  {recipieInfo.recipe.label}
</CustomLink>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:45:37