强制<Link>组件在next.js 13中滚动到布局顶部

huangapple go评论60阅读模式
英文:

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 &lt;Links&gt; 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 &lt;Links&gt; 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

&lt;Link&gt; 组件不是您问题的原因。默认情况下,它会在滚动位置 (0,0) 处打开其 href 属性指定的 URL,即网页的最顶部。这个行为由默认情况下为 true 的属性 scroll 指定(请参见此处的文档)。

您的问题可能是由于在 src/styles/globals.scss(如果您使用 sass)或 src/styles/globals.css(否则)中默认定义的样式引起的。检查是否在 htmlbody 选择器上定义了以下样式规则之一(overflowoverflow-xoverflow-yscroll-behavior),然后将其删除。

英文:

The &lt;Link&gt; 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.

huangapple
  • 本文由 发表于 2023年7月3日 22:54:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76605889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定