Next.js中使用Link组件动态拼接URL路径的问题求助
Next.js Link组件相对路径跳转异常修复
问题背景
项目采用Next.js App Router,目录结构为 /dashboard/[appid]/users/[userid]/user_info.tsx。在该页面内使用next/link组件,设置href="user_info",预期跳转到/dashboard/app_01/users/123123123/user_info,但实际点击后却跳转到根路径下的/user_info(该路径不存在)。
组件代码
'use client'; import Link from 'next/link'; import React from 'react'; import Image from 'next/image'; type sidebarbuttonprops = { text: string, to?: string, id: string, active?: string, disabled?: string[], icon?: string, getButtonValue: (buttonid: string) => void } export const SideBarButton = ({ text, to: link, id, active, disabled, icon, getButtonValue }: sidebarbuttonprops) => { let buttonActive: boolean = id == active ? true : false; let buttonDisabled: boolean | undefined = disabled?.includes(id); const handleClick = (e: React.MouseEvent<HTMLElement>) => { if (!buttonDisabled) { getButtonValue(id); } } return <Link className="sidebar-button" role='link' href={!buttonDisabled ? link! : ''} replace={false} onClick={handleClick}> <div className={`sidebar-button__container${buttonActive ? ' button_active' : ''}${buttonDisabled ? ' button_disabled' : ''}`} id={id}> <div className='sidebar-button__svg'> {icon != undefined && <Image src={icon!} alt="icon" width={25} height={25} />} </div> <div className='sidebar-button__text'> <span className='sidebar-button__span'> {text} </span> </div> </div> </Link>; }
异常表现
- 渲染后的HTML链接:
<a class="sidebar-button" role="link" href="user_info">[Some divs]</a> - 鼠标悬停时浏览器底部显示正确目标URL,但点击后跳转至根路径
- DevTools中直接点击链接可正常跳转至正确地址
修复方案
方案1:修正相对路径写法
将href="user_info"改为href="./user_info",通过添加.前缀明确告知Next.js基于当前路由路径拼接目标地址,无需手动编写完整URL。
方案2:调整点击事件绑定位置
问题根源是自定义onClick事件绑定在Link组件本身,干扰了Next.js内置的路由跳转逻辑。将点击事件移到Link内部的div元素上即可解决:
// 修改后返回部分代码 return <Link className="sidebar-button" role='link' href={!buttonDisabled ? link! : ''} replace={false}> <div className={`sidebar-button__container${buttonActive ? ' button_active' : ''}${buttonDisabled ? ' button_disabled' : ''}`} id={id} onClick={handleClick} // 将点击事件移至内部div > <div className='sidebar-button__svg'> {icon != undefined && <Image src={icon!} alt="icon" width={25} height={25} />} </div> <div className='sidebar-button__text'> <span className='sidebar-button__span'> {text} </span> </div> </div> </Link>;
备选方案:手动拼接路径(不推荐)
使用usePathname钩子获取当前路由路径,手动拼接目标地址:
'use client'; import { usePathname } from 'next/navigation'; // 组件内部 const pathname = usePathname(); const targetHref = `${pathname}/user_info`;
然后将Link的href设为targetHref,此方法较前两种繁琐,仅作备选。
总结
优先采用方案1或方案2,无需编写完整URL即可实现正确的相对路径跳转。
内容的提问来源于stack exchange,提问作者Nimink0
相关产品推荐
相关产品推荐

