简体   繁体   English

点击链接后如何go到页面顶部?

[英]How to go to the top of the page after clicking the link?

The problem is, it goes to the middle of the page whenever I navigate to a link in NextJS :问题是,每当我导航到NextJS中的链接时,它都会转到页面中间:

<Link href={`/products/${id}`} key={id}>
   <a>
      {/* other components */}
   </a>
</Link>

So i think the problem is that the link is on the middle of the page so when i click on the link it stays on the same position as where u clicked the link and not go at the top of the page.所以我认为问题在于链接位于页面中间,所以当我单击链接时,它与您单击链接的位置相同,而不是页面顶部的 go。 I know it doesn't make sense.我知道这没有意义。

I tried adding things like scroll={true} , or scroll={false} to the <Link> .我尝试将诸如scroll={true}scroll={false}之类的内容添加到<Link> Tried adding height: 100% to html and body in CSS .尝试将height: 100%添加到htmlCSS中的主体 I tried adding scroll-behavior: smooth;我尝试添加scroll-behavior: smooth; and other stuff.和其他东西。 The problem still stays.问题仍然存在。

Heres the video: https://drive.google.com/file/d/1CCgFCJb1fl9RRYmW5yp41US-0yuSqpfj/view?usp=sharing视频如下: https://drive.google.com/file/d/1CCgFCJb1fl9RRYmW5yp41US-0yuSqpfj/view?usp=sharing

In your page component, inside useEffect hook, put window.scrollTo(0,0)在您的页面组件中,在useEffect挂钩中,放置window.scrollTo(0,0)

useEffect(()=>{
  window.scrollTo(0,0);
},[])

Try to set scrollRestoration in some root component.尝试在某些根组件中设置 scrollRestoration 。

 history.scrollRestoration = 'manual';

you can use this hook and put id as it's dependency你可以使用这个钩子并将 id 作为它的依赖项

useEffect(() => {
   window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth"
        });
}, [id])

if you use it in nextjs, you need to put an if condition in this way如果在nextjs中使用的话,需要这样放一个if条件

useEffect(() => {

if(typeof window !== 'undefined'){
   window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth"
        });
   }
}, [id])


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

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