如何在React中使用i18next更改语言

时间:2020-03-31 15:56:05

标签: javascript reactjs internationalization i18next

我正在尝试将i18next翻译系统添加到我的React应用程序中,并且已经配置了所有内容,但是我似乎找不到如何更改语言的方法(例如,使用选择或按钮)。 / p>

我已经按照this简单指南进行了设置。 但是,没有关于如何手动更改语言的内容。 而且,如您所见here,有一个用于更改语言的函数,但它位于函数组件内部:

function Page() {
const { t, i18n } = useTranslation();

  const changeLanguage = lng => {
    i18n.changeLanguage(lng);
  };

  return ([...])
}

但是,我的组件是一个从组件扩展的类,它的工作方式似乎不同:

class Profile extends Component {
  [...]
}
export default withTranslation()(Profile);

那我该怎么办?我不知道。

2 个答案:

答案 0 :(得分:1)

它引发了一些我尚未解决的错误,但至少可以正常工作。 显然,当在函数组件中(例如之前列出的组件)时,在使用useTranslation时,您的t和i18n变量是通过调用useTranslation()获得的。 但是,使用类时,t和i18n是从this.props获取的。

所以,现在类看起来像这样:

import React, { Component } from "react";
import { withTranslation } from 'react-i18next';

class Profile extends Component {

  render() {
    const { t, i18n } = this.props;
    const changeLanguage = lng => {          
      i18n.changeLanguage(lng);
    };

    return (
      [...]
      <button onClick={() => changeLanguage('en')}>EN</button>
      [...]
    )
  }

  export default withTranslation()(UserProfile);

当我解决警告时,我将编辑答案,但是如果有人遇到相同的问题,我将保留此解决方案。

我得到的错误如下:

未捕获的错误:MobX提供程序:提供的商店集已更改。 看到: https://github.com/mobxjs/mobx-react#the-set-of-provided-stores-has-changed-error

答案 1 :(得分:0)

import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useTranslation } from "next-i18next";

// Use getServerSideProps or getStaticProps as convenience
export async function getServerSideProps({ locale }) {

  return {
    props: {
       ...(await serverSideTranslations(locale, ["common"]))
      },
  };

}

function YourComponent(props) {
   const { t, i18n } = useTranslation("common");
   console.log(i18n.language);
   return (<div>{i18n.language}</div>);
}

export default YourComponent;