i18next/i18n更改语言无法在整个网站中运行

4
我正在开发一个使用React和TypeScript的应用程序,需要支持网站翻译。我使用了i18next库。在主页面上,用户可以通过点击按钮来切换语言,该按钮会触发以下方法。
changeLang(lang:string):any{
        i18next.changeLanguage(lang).then(() => {
            this.props.close(); 
            i18next.options.lng = lang;
        });
    }

这对于更改主页的语言非常有效。然而,当我转到下一页时,它会返回到原始语言。我似乎无法使整个网站运行在不同的语言上。

我的 index.tsx 文件

import React from 'react';
import ReactDOM from 'react-dom';
import './styles/index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Amplify from 'aws-amplify';
import awsmobile from "./aws-exports";

import * as enTranslations from "./locales/en"; /* This import refers to all of the texts in english */
import * as ptTranslations from "./locales/pt" /* This import refers to all of the texts in portuguese */
import {initReactI18next, I18nextProvider} from 'react-i18next'; /* Import needed for the use of the dictionary/translation  */
import LanguageDetector from "i18next-browser-languagedetector"; /* Import needed for the use of the dictionary/translation  */
import i18next from "i18next"; /* Import needed for the use of the dictionary/translation  */


/* Configure Amplify on the client so that we can use it to interact with our backend services */
Amplify.configure(awsmobile);

/* Extract the translations */
const resources = {
  en: {messages: enTranslations}, 
  pt: {messages: ptTranslations}
};

/* Setting up the dictionary/translator */
const i18n = i18next.use(LanguageDetector).use(initReactI18next);

i18n.init({
  react: {
      wait: true,
  },
  resources: resources,
  lng: 'pt', /* Main Language */
  fallbackLng: 'en',
  keySeparator: '.',
  interpolation: {
      escapeValue: false,
  },
  ns: ['messages'],
  defaultNS: 'messages',
  fallbackNS: [],
});


ReactDOM.render(
  <I18nextProvider i18n={i18n}>
    <App />
  </I18nextProvider>,
  document.getElementById('root')
);

reportWebVitals();

我的网站所有页面都具有以下结构:
import { Component } from "react"
import { AuthProps } from "../../@types/auth"  // Imports Auth props used to authenticate user
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" /* Import needed to be able to use the custom FontAwesome font */
import { faChevronLeft } from "@fortawesome/free-solid-svg-icons" /* Import needed to get the desired font elements */

import i18next from "i18next"; /* Import needed for the use of the dictionary/translation  */
import { withTranslation } from 'react-i18next'; /* Import needed for the use of the dictionary/translation  */

import '../styles/views/change-password-confirm.css';


/**
 * Simple page that tells our user that his password has been changed
 */
class ChangePasswordConfirmation extends Component<AuthProps> {
  render() {
    return (
      <div className="change-password-confirm-background">  
      <div className="change-password-confirm-main">
        <div className="change-password-confirm-container">
          {/* Button used to go back to the login page */}
          <a href="/login" className="back"><FontAwesomeIcon icon={faChevronLeft}></FontAwesomeIcon></a>  
          <h1>{i18next.t('ChangePasswordConfirm.catchphrase')}</h1>
          <p>{i18next.t('ChangePasswordConfirm.secondaryText')}</p>
        </div>
      </div>
    </div>
    )
  }
}


export default withTranslation()(ChangePasswordConfirmation)

正如您所看到的,我使用 i18next.t('my-key') 获取翻译,并使用 "withTranslation()" 导出每个组件/页面。因此,我不知道为什么整个网站都没有改变语言。有人能帮帮我吗?

3个回答

0
所以我认为这里的问题是你在每个页面都从库中导入i18next。你应该做的是在你的索引文件中导出你创建的i18n,并在每个其他文件中导入它,而不是为每个组件导入一个新的i18next。另外,尝试将整个网站的语言值放在某种全局上下文中,以防你想在其他页面更改语言。希望这对你有帮助!

1
我尝试过那样做,但没有成功。我发现有效的方法是将 lng: 'pt' 更改为 lng: i18n.options.lng - Rodrigo Fernandes
是的,我也错过了。你将它设置为静态的东西,这就是问题所在。这种情况经常发生在我身上。无论如何,编码愉快! - Ziku

0

只是提醒大家,如果有人遇到同样的问题,请仔细检查locales/lang/translations.json的导入。我曾经复制粘贴错误,导致两种语言指向同一个翻译文件,因此没有翻译任何内容。


0

我在使用 i18n.changeLanguage() 方法时遇到了同样的问题。所以,最终我通过获取用户在浏览器中使用的当前语言来解决了这个问题。

const getUserLanguage = () => window.navigator.userLanguage || window.navigator.language;

window.navigator.language 对于大多数现代浏览器都有效,但为了保险起见,添加了 window.navigator.userLanguage

现在通过调用 getUserLangauge() 方法来获取 userlanguage。并根据此更改语言。

类似于这样的操作:

i18n.use(initReactI18next).init({
 resources,
 lng: `${userLanguage}`,
 fallbackLng: 'en',
 keySeparator: false,
 interpolation: {
  escapeValue: false,
  },
});

但是缺点是我们需要在切换语言时刷新页面。请注意,在生产环境中,它只会检查用户的浏览器设置并根据该设置呈现特定的语言。用户无法切换语言(唯一的切换方式是更改浏览器中的语言设置并刷新页面)。


请参考以下链接:https://locize.com/blog/how-to-internationalize-react-i18next/ - adrai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接