简体   繁体   English

NextJS 链接 href 默认值

[英]NextJS Link href default value

I need a default href value for Next/Link, as we do in plain html like below我需要 Next/Link 的默认 href 值,就像我们在下面的纯 html 中所做的那样

<a href='#' ></a>

I tried this to Link but it reloads the page, if I keep it empty it produces some error because its required attribute我试过这个Link ,但它重新加载页面,如果我保持它为空,它会产生一些错误,因为它的必需属性

<Link href='#'></Link>

Actually I am mapping a collection where some items does not have href so I need to put it blank and show some alert on click;实际上,我正在映射一个集合,其中某些项目没有href所以我需要将其留空并在点击时显示一些警报;

Conclusion结论

If you are using dynamic routing,如果您使用动态路由,

<Link href=":"></Link>

will fix your issue.将解决您的问题。

Explanation解释

Next.js only prefetches href if the link is local.如果链接是本地的,Next.js 仅预取 href。

When the href does not starts with "/", "?", or "#", Next.js constructs URL and checks if the URL is external or not .当 href 不以“/”、“?”或“#”开头时,Next.js 会构造 URL 并检查该 URL 是否为外部 URL

const resolved = new URL(url, locationOrigin)
return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)

When you pass empty string as href, Next.js thinks the link targets local URL, thus tries to prefetch the page, and fails if you have dynamic routing.当您将空字符串作为 href 传递时,Next.js 认为该链接以本地 URL 为目标,因此会尝试预取页面,如果您有动态路由,则会失败。

When you use : as href in <Link> , Next.js disables prefetch and fixes the issue.当您在<Link>中使用:作为 href 时,Next.js 会禁用预取并修复问题。 Although using : seems weird, it's actually recognized as a invalid "script" by the browser which should be ignored.虽然使用:看起来很奇怪,但实际上它被浏览器识别为无效的“脚本”,应该忽略它。

Though Next.js provides prefetch option, prefetch still occurs when you hover the link element even if you specify prefetch={false} , which causes the issue.尽管 Next.js 提供了预取选项,但即使您指定prefetch={false} ,当您悬停链接元素时仍会发生预取,这会导致问题。

如果你使用<Link href=''></Link>它不会产生任何错误,因为它有它的 required 属性并且它的值等于''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM