简体   繁体   English

如何使用 react-router v6 删除滚动位置

[英]How to remove scroll position with react-router v6

I have a react application and I am struggling to remove the previous page scroll-position .我有一个反应应用程序,我正在努力删除上一页scroll-position

Please I would appreciate it if you understand my problem before concluding.如果您在结束之前理解我的问题,我将不胜感激。

I do not want to preserve the scroll history .我不想保留scroll history I want it to always go back to the top of the page.我希望它始终回到页面顶部。

I have used the solution below to make the application scroll back to the top of the page whenever a user navigates to a new page.每当用户导航到新页面时,我已使用以下解决方案使应用程序滚动回页面顶部。

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

const ScrollToTop = ({ children }) => {
  const { pathname } = useLocation();

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

  return children || null;
};

export default ScrollToTop;

The above code is working very fine with no issues.上面的代码运行良好,没有任何问题。 What is not working for me is:对我不起作用的是:

When a user clicks a Button I created using Link from react-router-dom they are navigated to the new page (correct page), but the scroll-position is of the previous page (the page they are coming from).当用户单击我使用来自react-router-dom Link创建的Button时,他们将导航到新页面(正确的页面),但scroll-position是前一页(它们来自的页面)。

I have tried using these hooks.我试过使用这些钩子。

  • useLayoutEffect
  • withRouter (is removed from react-router v6) withRouter (从 react-router v6 中移除)
  • useHistory (is removed from react-router v6 useHistory (从 react-router v6 中移除
  • useNavigate

They are not working.他们不工作。

How can I resolve this?我该如何解决这个问题? Or is there something I am missing?还是我缺少什么?

I have also tried implementing the solution below.我也尝试过实施下面的解决方案。 But wont work.但不会工作。

import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

    function ScrollToTop({ history }) {
      useEffect(() => {
        const unlisten = history.listen(() => {
          window.scrollTo(0, 0);
        });
        return () => {
          unlisten();
        }
      }, []);
    
      return (null);
    }
    
    export default withRouter(ScrollToTop);

每次用户进入该屏幕时,您都可以滚动到顶部,使用焦点挂钩https://reactnavigation.org/docs/function-after-focusing-screen/

After 4 hours of research and trying and errors.经过 4 小时的研究和尝试和错误。 I have found the solution to this.我已经找到了解决方案。

In react-router v6.react-router v6. You do not need to your window.你不需要你的窗口。 on your useEffect You just need to have your code like this:在你的useEffect上你只需要这样的代码:

useEffect(() => {
    document.body.scrollTo(0, 0); 
});

I found the answer here , and researched more on it.我在这里找到了答案,并对其进行了更多研究。

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

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