Next.js 如何在页面路由时保持滚动位置

15

我目前正在使用Next.js脚手架制作网站。

以下是我的路由代码:

import Link from 'next/link'


<Link href={{ pathname: '/some-url', query: { param: something } }}>
  <div>
    <button type="button" onClick={handleClickMore}><span>+ More</span></button>
  </div>
</Link>

当我点击这个<Button>时,我不想滚动位置被移动。但是你知道,当新页面正在路由时,它会移到顶部。有人有关于在加载新页面时如何保持滚动位置的想法吗?

3个回答

30
<Link scroll={false} href="/"><a>Home</a></Link>

scroll={false} will disable the scroll to top on page changes for that specific link.

参考: https://github.com/zeit/next.js/issues/3950

这个问题是关于使用Next.js时在服务器端渲染页面时出现的。如果您在页面中使用了window对象,那么在服务器端渲染时会抛出错误,因为window对象只存在于浏览器环境中。解决这个问题的方法是在使用window对象之前先检查它是否存在。


不适用于Next.js 13.4。 - Nathan Bernard
不适用于Next.js 13.4。 - undefined
似乎仍然存在一个问题。https://github.com/vercel/next.js/discussions/47781 - Manuel Bichler
问题已解决。https://github.com/vercel/next.js/issues/50105#issuecomment-1619782873 - user1473249581

3

感谢LDS的回答,我想我找到了答案。

使用Router.push()时页面滚动位置不会移动。

解决方案代码如下:


import Link from 'next/link'

const handleClickMore = () => {
  Router.push({
    pathname: '/story/category/movie/movielist',
    query: { category: props.category, page: (parseInt(props.page) + 1) }
  })
}


<Link href={{ pathname: '/some-url', query: { param: something } }}>
  <div>
    <button type="button" onClick={handleClickMore}><span>+ More</span></button>
  </div>
</Link>

提醒一下,我已经跳过了组件声明的代码。


1
这似乎在接下来的10个版本中会出现问题:( - Ziker

-13

You may disable the scrolling There are two examples bellow

.scrollDisabled {   
    position: fixed;
    margin-top: 0;// override by JS to use acc to curr $(window).scrollTop()
    width: 100%;
}
JS

var y_offsetWhenScrollDisabled=0;

function disableScrollOnBody(){
    y_offsetWhenScrollDisabled= $(window).scrollTop();
    $('body').addClass('scrollDisabled').css('margin-top', -y_offsetWhenScrollDisabled);
}
function enableScrollOnBody(){
    $('body').removeClass('scrollDisabled').css('margin-top', 0);
    $(window).scrollTop(y_offsetWhenScrollDisabled);
}



Another way 



.stop-scrolling {
  height: 100%;
  overflow: hidden;
}


$('body').addClass('stop-scrolling')


非常感谢您的回答,但在Next.js样板中通常不会混合使用jQuery库。 - LeeMinHo
嘿,你可以通过谷歌搜索以上函数来将jQuery更改为Next.js,例如$(window).scrollTop()将变成如下生命周期方法:componentDidMount() { window.addEventListener('scroll', this.onScroll, false); }componentWillUnmount() { window.removeEventListener('scroll', this.onScroll, false); } - LDS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接