首页 > 解决方案 > 更改 Gatsby 链接行为 - 页面更改时停止滚动动画

问题描述

我确信这将是一个非常直接的答案,但我一生都无法弄清楚如何让我的 Gatsby/React 网站在没有滚动过渡效果的情况下从新页面的顶部开始我点击一个内部链接。

示例:在我的主页上,我滚动到底部,然后单击一个链接将我带到“关于我”页面。About Me 页面加载时浏览器滚动位置仍位于页面底部,然后窗口滚动到页面顶部。这只需要几毫秒,但是当我点击一个链接时,我想从页面顶部开始,没有任何过渡。

这些链接都是标准的 Gatsby 链接:

    <Link className="" to="/aboutme/">
      About Me
    </Link>

谢谢!

编辑

添加我的布局包装器,添加了 useScrollRestoration 钩子:

import React from 'react'
import PropTypes from 'prop-types'
import useScrollRestoration from 'gatsby'

import NavBar from './NavBar/NavBar'
import Footer from './Footer/Footer'

import './layout.scss'

const Layout = ({ children }) => {
  const aboutMeScrollRestoration = useScrollRestoration(`page-component-main`)

  return (
    <>
      <NavBar />
      <main className="bumpdown" {...aboutMeScrollRestoration}>
        {children}
      </main>
      <Footer />
    </>
  )
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

标签: reactjsgatsby

解决方案


经过大量的谷歌搜索,我最终设法解决了这个问题。它似乎不是滚动恢复问题,而是引导问题。在 bootstrap/scss/_reboot.scss 中有以下代码:

:root {
  font-size: $font-size-root;

  @if $enable-smooth-scroll {
    @media (prefers-reduced-motion: no-preference) {
      scroll-behavior: smooth;
    }
  }
}

这可以使用$enable-reduced-motion: true;$enable-smooth-scroll: false;在引导覆盖中关闭,当新页面打开时停止滚动行为。

我正在使用 enable-smooth-scrolling:false 选项,因为另一个选项可能会产生进一步的连锁反应。


推荐阅读