【发布时间】:2021-01-20 19:07:19
【问题描述】:
// import Link from "next/link";
<Link href="/">Home</Link>
指向/ 的链接刷新页面。每当用户导航到主页时,我能做些什么来阻止页面刷新吗?
【问题讨论】:
标签: next.js
// import Link from "next/link";
<Link href="/">Home</Link>
指向/ 的链接刷新页面。每当用户导航到主页时,我能做些什么来阻止页面刷新吗?
【问题讨论】:
标签: next.js
docs 声明如下:在网站上的页面之间链接时,您使用 HTML 标记。在 Next js 中,您使用来自 next/link 的链接组件来包装标签。它允许您对应用程序中的不同页面进行客户端导航。
做事
<Link href="/">
<a>
Home
</a>
</Link>
【讨论】:
使用这个钩子,您将永远不必再使用Link。只需使用常规的 HTML 锚点,它们就会按您的预期工作。
// useNextClickHandler.ts
import type { Router } from 'next/router'
import { useEffect } from 'react'
/**
* Place this in a Next.js's _app.tsx component to use regular anchor elements
* instead of Next.js's <code>Link</code> component.
*
* @param router - the Next.js router
*/
export default function useNextClickHandler(router: Router): void {
useEffect(() => {
async function onClick(event: MouseEvent) {
// Only handle primary button click
if (event.button !== 0) {
return
}
// Use default handling of modifier+click events
if (
event.metaKey ||
event.ctrlKey ||
event.altKey ||
event.shiftKey
) {
return
}
const anchor = containingAnchor(event.target)
// Only handle anchor clicks
if (!anchor) {
return
}
// Use default handling of target="_blank" anchors
if (anchor.target === '_blank') {
return
}
// If the link is internal, prevent default handling
// and push the address (minus origin) to the router.
if (anchor.href.startsWith(location.origin)) {
event.preventDefault()
await router.push(anchor.href.substr(location.origin.length))
}
}
window.addEventListener('click', onClick)
return () => window.removeEventListener('click', onClick)
}, [router])
}
function containingAnchor(
target: EventTarget | null
): HTMLAnchorElement | undefined {
let parent = target
while (
parent instanceof HTMLElement &&
!(parent instanceof HTMLAnchorElement)
) {
parent = parent.parentElement
}
return parent instanceof HTMLAnchorElement ? parent : undefined
}
// _app.tsx
export default function App({
Component,
pageProps,
router,
}: AppProps): JSX.Element {
useNextClickHandler(router)
【讨论】:
其他替代方法是使用next/router 并利用onClick 事件。
import Router from "next/router";
<a onClick={() => Router.push("/")}">
Home
</a>
【讨论】: