简体   繁体   English

如何解决反应自动滚动问题?

[英]How to fix react auto scroll issue?

I am using react to create my project.我正在使用 react 来创建我的项目。 The issue I am having is if I scroll to any page and then to go another page I end up in the same place on the top of the page.我遇到的问题是,如果我滚动到任何页面,然后滚动到 go 另一个页面,我最终会在页面顶部的同一位置。 How can I fix this issue?我该如何解决这个问题?

you can use Window.scrollTo or element.scrollIntoView function to resolve the problem您可以使用Window.scrollToelement.scrollIntoView function 来解决问题

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

or if you want scroll behavior或者如果你想要滚动行为

window.scrollTo({
  top: 0,
  left: 0,
  behavior: 'smooth'
});

but this is not the best way to do it in every component so you can use custom hooks to implement and use it everywhere但这不是在每个组件中执行此操作的最佳方法,因此您可以使用自定义挂钩来实现并在任何地方使用它

import react, { useEffect } from "react";

const useTop = function () {
  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);
};

export default useTop;

click to view demo 点击查看演示

let's figure it out of the element.scrollIntoView function and the use case if we need to scroll to an element but we don't know the height and width of the element from the viewport so that's why we just use element.scrollIntoView function to resolve that.让我们从element.scrollIntoView function 和用例中找出它,如果我们需要滚动到一个元素但我们不知道视口中元素的高度和宽度,这就是为什么我们只使用 element.scrollIntoView function 来解决那。 we can manually calculate the height and width of the element from the viewport using the element.getBoundingClientReact function but we need a lot of boilerplate code needed to implement我们可以使用element.getBoundingClientReact function 从视口手动计算元素的高度和宽度,但我们需要大量的样板代码来实现

with the use of custom, hooks can use scroll events whenever we needed通过使用自定义,钩子可以在需要时使用滚动事件

const useTop = function () {
      const scroll = (ref) => {
        ref.current.scrollIntoView({ behaviour: "smooth" });
      };
    
      return { scroll };
    };
    
    export default useTop;

click to view demo 点击查看演示

Try this:尝试这个:

componentDidMount() {
window.scrollTo(0, 0)
}

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

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

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