如何在 NextJS 的新标签页中打开链接?我试过这个:
<Link href="https://twitter.com/" passHref>
<a target="_blank">
<div className={`${dark ? styles.iconTwitterWhite : styles.iconTwitter} mr-3`} />
</a>
</Link>
Run Code Online (Sandbox Code Playgroud)
它在新标签中打开链接,但我有一条ESLint消息说:
ESLint: The href attribute is required for an anchor to be keyboard accessible. Provide a valid, navigable address as the href value. If you cannot provide an href, but still need the element to resemble a link, use a button and change it with appropriate styles.
Run Code Online (Sandbox Code Playgroud)
还有另一种方法吗?
kag*_*six 69
2022 年 11 月 答复:
随着 Next 13 的发布,该<Link/>组件现在在内部呈现<a/>标签,因此您不再需要添加子<a/>标签。
这意味着为了在新选项卡中打开链接,您应该能够执行以下操作:
<Link href="https://google.com" rel="noopener noreferrer" target="_blank"> Google </Link>
cor*_*ons 52
我听说有些情况下你想坚持使用Link(国际化的东西Link有帮助),这样你就可以使用passHref(它只是将其传递href给直接的孩子),如下所示:
<Link href="/" passHref>
<a target="_blank" rel="noopener noreferrer">
Foo
</a>
</Link>
Run Code Online (Sandbox Code Playgroud)
小智 21
我的项目中的路径:public/NameFile/NamePdf.pdf
注意:1)不要忘记“Link”的依赖=> import Link from 'next/link' 2)如您所见,我没有在链接中添加“public”。>> 因为你根本不需要放置它,因为 NextJs 很聪明。
<Link href="./NameFile/NamePdf.pdf" download>
<a target="_blank">
{your code ......}
</a>
</Link>
Run Code Online (Sandbox Code Playgroud)
eno*_*och 18
由于这是一个外部链接,您不需要使用 Link
<a target="_blank" href="https://twitter.com/" rel="noopener noreferrer">
<div className={`${dark ? styles.iconTwitterWhite : styles.iconTwitter} mr-3`} />
</a>
Run Code Online (Sandbox Code Playgroud)
小智 9
我尝试了下面的代码片段,它工作正常,没有错误。否则,我的本地主机可以正常工作,但当我部署到 Vercel 时,它会在构建日志中出现错误。因此,我尝试了此代码片段,它可以在本地主机和 Vercel 上正常工作。
<Link href="https://twitter.com/">
<a target="_blank" rel="noopener noreferrer" className='link-item'>
<div className={`${dark ? styles.iconTwitterWhite : styles.iconTwitter} mr-3`} />
</a>
</Link>Run Code Online (Sandbox Code Playgroud)
确保将属性target="_blank"添加到标签中。rel="noopener noreferrer"a
在 next.js 13 版本中,您可以使用它。
<Link href="https://facebook.com" target="_blank"> Facebook </Link>
Run Code Online (Sandbox Code Playgroud)
小智 8
从Next13开始, <Link> 组件不应该有 <a> 子组件。因此,您不能将目标放在那里,而是将其设置在 <Link> 上,如下所示:
<Link
href="/some-route"
className="some classes"
target="_blank"
>
{children}
</Link>
Run Code Online (Sandbox Code Playgroud)
但是,如果您坚持在链接内使用 <a> ,则需要传递 LegacyBehavior 属性:
<Link href="/about" legacyBehavior>
<a>About Us</a>
</Link>
Run Code Online (Sandbox Code Playgroud)
检查下一个文档
使用下一个路由器
此方法与客户端转换一起使用,以将页面内容向另一个方向移动。这种行为对于将页面导航到另一个选项卡非常有用。
import { useRouter } from "next/router"
export default function App() {
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
return (
<div onClick={() => openInNewTab("/path")}>
Button
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14222 次 |
| 最近记录: |