繁体   English   中英

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

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

我正在使用 Next.js 的内置国际化功能来更改我的应用程序的语言,除了一种不良行为外,一切都运行良好:

尽管将路由器的滚动选项设置为 false ,但调用changeLanguage function 会导致页面滚动到顶部。

请注意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 react-select 库用于显示标志的下拉列表,单击每个标志changeLanguage以相应地更新语言环境。

接下来router.push接受三个参数。

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

应该

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

暂无
暂无

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

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