简体   繁体   English

Next.js — router.push 将页面滚动到顶部,尽管滚动选项设置为 false

[英]Next.js — router.push scrolls page to the top despite scroll option set to false

I am using Next.js' built-in internationalisation features to change my app's language and everything is working perfectly except for one undesirable behaviour:我正在使用 Next.js 的内置国际化功能来更改我的应用程序的语言,除了一种不良行为外,一切都运行良好:

Calling the changeLanguage function results in the page scrolling to the top in spite of setting the router's scroll option to false .尽管将路由器的滚动选项设置为 false ,但调用changeLanguage function 会导致页面滚动到顶部。

Please note that Next.js - router.push without scrolling to the top and Next.js maintain scroll position when page Routing did not solve my issue.请注意Next.js - router.push 没有滚动到顶部Next.js 在页面路由没有解决我的问题时保持滚动 position

import { useRouter } from "next/router";
import Select, { components } from "react-select";

const LanguageToggler = () => {

  const router = useRouter();
  const { locale, pathname, locales, asPath } = router;

  const changeLanguage = (e) => {
    const locale = e.value; // is equal to one of these values: ['en', 'sv', 'ru', 'fr']
    router.push(pathname, asPath, { locale }, { scroll: false });
  };

 return (
      <Select
        ...irrelevant
        onChange={changeLanguage}
        components={{
          Option: CustomSelectOption,
        }}
      />
    )
};

export default LanguageToggler;

PS The react-select library is used to display a dropdown list of flags, clicking each flag summons changeLanguage to update the locale accordingly. PS react-select 库用于显示标志的下拉列表,单击每个标志changeLanguage以相应地更新语言环境。

Next router.push accepts three parameters.接下来router.push接受三个参数。

router.push(pathname, asPath, { locale }, { scroll: false });

should be应该

router.push(pathname, asPath, { locale, scroll: false });

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

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