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

React+TypeScript中如何配置指向子域名的导航链接

解决React导航菜单中子域名链接被错误拼接的问题

问题出在你用了React Router的<Link>组件处理外部URL。<Link>是专门给内部路由设计的,当你传入像https://sub.domain.com/这种完整外部地址时,它会把当前页面路径和这个地址拼接,导致出现localhost:3000/page-currently-on/https://sub.domain.com/这种错误路径。

解决步骤:

  1. 区分内部路由和外部链接:在渲染导航项时,判断URL是否为外部地址(包含http://或https://),外部链接用普通的<a>标签代替<Link>。
  2. 移除无效的路由配置:App.tsx里不需要为外部URL配置<Route>,直接删掉那项即可。

修改后的代码示例:

Navigation.tsx

const ROUTES = [
  {url: RouteName.Home,      name: "Home"},
  {url: RouteName.About,     name: "About"},
  {url: RouteName.Service,   name: "Service"},
  {url: RouteName.Portfolio, name: "Portfolio"},
  {url: RouteName.Contact,   name: "Contact"},
];

<Menu className="Menu">
  {ROUTES.map((item) => {
    const isExternal = item.url.startsWith('http://') || item.url.startsWith('https://');
    return (
      <li key={item.url} className={pathname === item.url ? "active" : ""}>
        {isExternal ? (
          <a href={item.url} target="_blank" rel="noopener noreferrer">
            {item.name}
          </a>
        ) : (
          <Link to={item.url}>{item.name}</Link>
        )}
      </li>
    );
  })}
</Menu>

App.tsx

<Routes>                      
  {/* 移除外部URL的Route配置 */}
  <Route path={RouteName.Home} element={<><TopNav /><Home /></>} />
  <Route path={RouteName.About} element={<><TopNav /><About /></>} />
  <Route path={RouteName.Service} element={<><TopNav /><Service /></>} />
  <Route path={RouteName.Contact} element={<><TopNav /><Contact /></>} />
</Routes>

补充说明:

  • target="_blank":让外部链接在新标签页打开(如果不需要可以去掉)。
  • rel="noopener noreferrer":是安全属性,防止新打开的页面通过window.opener访问原页面,避免安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:15:49