过渡后的React Scroll页面到顶部
我希望当单击网站中的另一页时,我的应用程序可以转到页面顶部。我使用了以下代码: https://v5.reactrouter.com/web/web/guides com /滚动率并放入一个单独的文件。
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
我尝试过的是:
我放置了< scrolltopop/>
< switch>< switch/>
以及< browserrouter />
如文档中(这些是在单独的文件中)。
与文档不同,我的应用程序中的&lt; app /&gt; < /code>在单独的文件中,因此
&lt; scrolltotop /&gt; < /code>没有放置在其附近。
当我委托时,我会发现它在正确的实例上被击中(当有页面更改时),但是什么也不会发生。我还研究了许多有关同一问题的堆叠式帖子,但我无法纳入他们的建议。
有什么可能的问题:
调用 window.scrollto(0,0)在功能外部似乎不起作用。此功能是否有替代方案?
&lt; scrolltotop /&gt; < /code>的放置是否不正确?是否必须在
&lt; app /&gt; < /code>附近调用它?
I want my application to go to the top of the page when another page within the site is clicked. I have used the code from: https://v5.reactrouter.com/web/guides/scroll-restoration and put in a separate file.
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
What I have tried:
I have placed <ScrollToTop />
before <Switch />
and after <BrowserRouter />
as in the docs (these are in separate files).
Unlike the docs, the <App />
in my application is in a separate file, so <ScrollToTop />
is not placed near it.
When I console.log, I see it being hit at the correct instance (when there is a page change), but nothing occurs. I have also looked into many stackoverflow posts concerning the same issue, but I could not incorporate their suggestions.
What are possible issues:
Calling window.scrollTo(0, 0) outside the function does not seem to work. Are there any alternatives to this function?
Is the placement of <ScrollToTop />
incorrect? Does it have to be called near the <App />
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经走了一半。您确实不需要为其创建一个组件。您可以创建一个自定义钩子并将其放在
&lt; app /&gt; < /code>中,然后将其拨打:
每当您转到新页面时,它都会滚动到页面顶部。
You have already gone half the way. You really don't need to create a component for it. You can create a custom hook and place it in your
<App />
and then call it:This way whenever you go to a new page, it scrolls to the top of the page.