我有下一个 js web,它有一些链接可以在页脚上重定向,所以如果我点击那个链接,它首先会被重定向到那个页面,向下滚动(当前位置),然后向上滚动我不想向上滚动,默认情况下,它应该在页面顶部,任何建议都将不胜感激
<NextLink href="/news">
<a onClick={() => trackClick("News")}>In the News</a>
</NextLink>
您可以像这样将滚动设置为 false:
<NextLink href="/news" scroll={false}>
<a onClick={() => trackClick("News")}>In the News</a>
</NextLink>
要在没有动画的情况下自动滚动到顶部,您必须在 _app.ts 或特定页面上添加 useEffect:
import { useRouter } from "next/router";
const App = ({ Component, pageProps }: AppProps) => {
const { pathname } = useRouter();
useEffect(() => {
// some browsers (like safari) may require a timeout to delay calling this
// function after a page has loaded; otherwise, it may not update the position
window.scrollTo(0, 0, behavior: 'instant');
}, [pathname]);
return <Component {...pageProps} />
};
export default App;