【问题标题】:Get current language next-i18next获取当前语言 next-i18next
【发布时间】:2020-09-26 06:58:39
【问题描述】:

我正在使用 NextJS 和 next-i18next。这是我的主页:

import {withTranslation}  from '../config/next-i18next';

const Home = function Home() {
  return (<div>test</div>)
};

Home.getInitialProps = async () => {
  return {namespacesRequired: ['home']}
};

export default withTranslation('home')(Home);

我想要的是在组件/页面中获取当前语言,我该怎么做?

【问题讨论】:

    标签: node.js reactjs internationalization next.js i18next


    【解决方案1】:

    withTranslation 注入 i18n 对象。

    import {withTranslation}  from '../config/next-i18next';
    
    const Home = function Home({ i18n }) {
      return (<div>{i18n.language}</div>)
      // ----------------^
    };
    
    Home.getInitialProps = async () => {
      return {namespacesRequired: ['home']}
    };
    
    export default withTranslation('home')(Home);
    

    或者使用 Hooks,

    import {useTranslation}  from '../config/next-i18next';
    
    const Home = function Home() {
      const { i18n } = useTranslation('home');
      return (<div>{i18n.language}</div>)
      // ----------------^
    };
    
    Home.getInitialProps = async () => {
      return {namespacesRequired: ['home']}
    };
    
    export default Home;
    

    【讨论】:

      【解决方案2】:

      借助 Next.js,您还可以使用 useRouter 挂钩。

      import {withTranslation}  from '../config/next-i18next';
      import { useRouter } from 'next/router'
      
      const Home = function Home() {
      const router = useRouter()
      const currentLang =  router.locale // => locale string eg. "en"
        return (<div>test</div>)
      };
      
      Home.getInitialProps = async () => {
        return {namespacesRequired: ['home']}
      };
      
      export default withTranslation('home')(Home);
      

      【讨论】:

      • 只有在修改 next.config.js 后启用它才有效。您可以启用最多 100 个“已知”语言环境(我想支持任何可能的语言环境,我将其设置在 550 个语言环境内,但它会引发错误,说明存在此限制)。此外,它还会更改您的 url,使其始终位于语言环境中的路径上,mysite.com/mypage/ -> mysite.com/en-US/mypage 可能是您不想要的行为。
      猜你喜欢
      • 1970-01-01
      • 2013-10-07
      • 2020-11-24
      • 2020-07-06
      • 2021-08-14
      • 1970-01-01
      • 2021-06-14
      • 2020-08-01
      • 1970-01-01
      相关资源
      最近更新 更多