Next.js - router.push 不滚动到顶部 [英] Next.js - router.push without scrolling to the top

查看:39
本文介绍了Next.js - router.push 不滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过从 next/router 导入 useRouter 来使用来自 next 的路由器.

I am using router from next by importing useRouter from next/router.

我正在尝试找到一个解决方案,当我更改 URL 的查询时,它不会滚动到页面顶部.有什么解决办法吗?我知道 Next 中的 Link 组件具有该选项,但我需要使用 Router 组件.我的下一个版本是 10.0.5.

I am trying to find a solution which will not scroll to the top of the page when I change the query of the URL. Is there any solution? I know that Link component from Next has that option, but I need to use Router component. My next version is 10.0.5.

const router = useRouter();

const changeCurrency = (newCurrency) => {
   //Do some stuff here

    Router.push({
        pathname: router.pathname,
        query: { ...router.query, currency: newCurrency.value },
    });
};

推荐答案

router.push 有一个 scroll 选项,它是 true by默认.你可以这样关闭它:

router.push has a scroll option, it is true by default. You can turn it off like this:

const router = useRouter();

async function navigate(newCurrency) {
  router.push({
    pathname: router.pathname,
    query: { ...router.query, currency: newCurrency.value },
  }, undefined, { scroll: false });
}

router.push 在选项对象中接受大部分(如果不是全部)next/link 的道具.你可以在这里查看它们:https://nextjs.org/docs/api-reference/next/链接

router.push accepts the most of (if not all) next/link's props in the options object. You can check them here: https://nextjs.org/docs/api-reference/next/link

这篇关于Next.js - router.push 不滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆