英文:
Force <Link> component to scroll to top of layout in next.js 13
问题
我在应用程序路由中有一个动态路由,具有共享的父布局。页面内有一些动态填充的<Links>,希望的行为是当单击链接时,将滚动重置到页面顶部。然而,默认行为似乎保留当前滚动位置。
这是文件结构:
layout.tsx
[slug] / page.tsx
在每个page.tsx中,我有一个相关帖子组件,此组件包含到路由中其他slug的<Links>。测试版期间的另一个回答建议在布局上添加useEffect,但是将布局强制转换为客户端组件似乎对于这个简单功能来说有些过头了。
感谢您提前的建议。
英文:
I have a dynamic route in the app router, with a shared parent layout. I have some <Links> that are dynamically populated within the page, and the desired behaviour would be that when the links are clicked, scroll is reset to the top of the page. The default behaviour however seems to retain the current scroll position.
Here is the file structure:
layout.tsx
[slug] / page.tsx
In each page.tsx I have a related posts component, and this component houses the <Links> to other slugs in the route. Another answer during the beta suggested adding a useEffect on the layout, however forcing the layout into a client component seems like overkill for this simple functionality.
Thanks in advance for the advice.
答案1
得分: 0
<Link>
组件不是您问题的原因。默认情况下,它会在滚动位置 (0,0)
处打开其 href
属性指定的 URL,即网页的最顶部。这个行为由默认情况下为 true
的属性 scroll
指定(请参见此处的文档)。
您的问题可能是由于在 src/styles/globals.scss
(如果您使用 sass)或 src/styles/globals.css
(否则)中默认定义的样式引起的。检查是否在 html
或 body
选择器上定义了以下样式规则之一(overflow
、overflow-x
、overflow-y
、scroll-behavior
),然后将其删除。
英文:
The <Link>
component is not the cause of your issue. By default it opens the URL specified as its href
prop at the scroll position (0,0)
that is at the top-most of the web page. This is behavior is specified by the attribute scroll
which is true
by default (See the Doc here).
Your problem probably comes from the styles defined by default in src/styles/globals.scss
(if you're using sass) src/styles/globals.css
(otherwise) . Check if one of the following style rules (overflow
, overflow-x
, overflow-y
, scroll-behavior
) is defined either on the html
or body
selector then remove it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论