在下一个js中平滑滚动

Man*_*son 12 smooth-scrolling reactjs next.js

如何在 Next.js 中将滚动效果设置为平滑(全局)?我尝试在全局 css 上执行此操作,但它停用了 Next js 已有的滚动到顶部功能。

我也尝试了在互联网上找到的这个解决方案,但它也不起作用。

 componentDidMount() {
 Router.events.on('routeChangeComplete', () => {
    window.scroll({
       top: 0,
       left: 0,
       behavior: 'smooth'
    });
 });
Run Code Online (Sandbox Code Playgroud)

}

小智 42

在 html 或 body 中添加滚动行为:平滑。然后添加

<Link href="#someid" scroll={false}>
Run Code Online (Sandbox Code Playgroud)

作品

  • 谢谢哥们。我遇到了类似的问题,并且不知道 nextjs 链接有一个滚动道具。这很有帮助。 (2认同)

Cha*_*ANI 14

只需将style={{scrollBehavior:'smooth'}}标签 Html 放入“ _document.tsx ”文件中即可。

喜欢 :

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html className='scroll-smooth' style={{scrollBehavior:'smooth'}}>
        <Head>
          <link rel='icon' href='/favicon.ico' />
          <meta
            name='description'
            content='A place to find a great film to watch'
          />
        </Head>
        <body className='bg-gray-50 screen'>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这也会在页面路由上添加不需要的滚动。 (4认同)

Man*_*son 0

我解决了!您可以使用 npm 包执行此操作(不是全局的,但工作正常) react-scroll 这是链接:https: //www.npmjs.com/package/react-scroll

  • 为简单的事情添加第 3 方包根本不是一个好的做法。 (3认同)