【问题标题】:React - Prevent scrolling to top after changing query paramsReact - 更改查询参数后防止滚动到顶部
【发布时间】:2021-09-30 12:27:05
【问题描述】:

在我的 Gatsby 应用程序中,我有一个包含分页组件的页面。

默认路径为:'/?page=1',点击分页按钮变为'/?page=2'' /?page=3' ...

我正在“保存”路径中的页码,因为我希望浏览器记住用户之前所在的页码,以防他点击返回按钮 em> 浏览器。

这种方法的问题是每次路径改变时,页面都会自动滚动到顶部,我不希望它滚动到顶部。

有人知道防止这种情况的方法吗?

【问题讨论】:

    标签: reactjs react-router gatsby


    【解决方案1】:

    这是默认的 Gatsby 行为(称为Scroll Restoration)。您已经公开了useScrollRestoration 钩子以使用此行为(并根据您的规范进行相应更改)。例如:

    import { useScrollRestoration } from "gatsby"
    import countryList from "../utils/country-list"
    export default function PageComponent() {
      const ulScrollRestoration = useScrollRestoration(`page-component-ul-list`)
      return (
        <ul style={{ height: 200, overflow: `auto` }} {...ulScrollRestoration}>
          {countryList.map(country => (
            <li>{country}</li>
          ))}
        </ul>
      )
    }
    

    在你的情况下,你应该添加你的元素类名。

    相关的 GitHub 线程:

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2019-11-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 2018-04-01
      相关资源
      最近更新 更多