next-i18next-是否可以动态更改默认语言?

时间:2020-09-29 10:19:51

标签: javascript next.js next-i18next

我正在使用next-i18next处理next.js应用程序的国际化。

是否可以动态更改默认语言? 例如基于顶级域名?

const defaultLanguage = topLevelDomain === "de" : "de" ? "it";

编辑:我也使用localeSubpaths,所以这就是我试图调查该主题的原因。

2 个答案:

答案 0 :(得分:1)

对于使用 Nextjs v10.0.0 的人来说 here,我们必须使用最新的 configurations

next-i18next.config.js

module.exports = {
  i18n: {
    defaultLocale: 'it',
    locales: ['it', 'de'],
  },
}

next.config.js

const { i18n } = require('./next-i18next.config')

module.exports = {
  i18n,
}

要更改语言,我们必须使用 next/linknext/router

import Link from 'next/link'
import { useRouter } from 'next/router'
import { Menu } from 'antd'
import { BorderOutlined, CheckSquareOutlined } from '@ant-design/icons'

.
.
.

export default function YourComponent() {
  .
  .
  const router = useRouter()

  const selectedLang = lang => {
    return router.locale === lang ? <CheckSquareOutlined /> : <BorderOutlined />
  }

  return (
    .
    .
    .
    <Menu onClick={handleLangMenuClick}>
      <Menu.Item key="it" icon={selectedLang('it')}>
        <Link href={router.pathname} locale="it" >
          <a>Italian</a>
        </Link>
      </Menu.Item>
      <Menu.Item key="en" icon={selectedLang('de')}>
        <Link href={router.pathname} locale="de" >
          <a>German</a>
        </Link>
      </Menu.Item>
    </Menu>
    .
    .
  )

.
.
}

但你必须记住:

  1. 首次渲染时,默认语言将始终引用浏览器发送的 Accept- Language 标头。换言之,默认语言将基于目标用户的浏览器语言设置。

    假设浏览器发送的 Accept-Language 标头如下(deit 都存在):

    Accept-Language: de, de;q=0.9, it;q=0.8, en;q=0.7, *;q=0.5
    
    # Note: the `q` value may be differs, the bigger will get the most priority
    

    那么默认语言将为 German,忽略 defaultLocale 处的配置 next-i18next.config.js

  2. 如果 deit 均未在 Accept-Language 中列出,例如:

    Accept-Language: fr-CH, fr;q=0.9, en;q=0.8, cn;q=0.7, *;q=0.5
    

    那么默认语言将是 Italian 遵循我们的配置 制作。

  3. 出于开发目的,我们可以更改浏览器语言设置(我使用 google chrome) 在 chrome://settings/?search=language 并订购语言 根据您的喜好。

  4. 我们可以通过编程方式为下一次渲染设置默认语言 根据目标用户的浏览器添加 NEXT_LOCALE cookie 选择。示例:

    import cookie from 'react-cookies'
    .
    .
    .  
    
    export default function YourComponent() {
      .
      .
    
      setDefaultLang = (lang) => {
         cookie.save('NEXT_LOCALE', lang)
      }
      .
      .
      .
    }
    
  5. 请务必查看 documentation 以获取最新更新。

答案 1 :(得分:0)

本文解释了从 next-i18next v7 到 v8 的迁移https://github.com/isaachinman/next-i18next/issues/1040

var languages = [
  ['English', 'en'],
  ['French', 'fr']
]

export default function YourComponent() {
  const router = useRouter();

  const handleLocaleChange = (data)=>{
    router.replace(router.pathname, router.pathname, { locale: data })
  }
  return (
    <Menu onClick={handleLangMenuClick}>
      {languages.map((row, index) => (
      <Menu.Item key="en" onClick={(row[1]) =>handleLocaleChange(row[1])}>
          <a>{row[0]}</a>
      </Menu.Item>      
      )}

    </Menu>
   )
}