React中的SO i18next反应式翻译

时间:2018-06-22 22:58:25

标签: reactjs internationalization translation reactive i18next

我在尝试使用 React 上的 i18next 进行反应式翻译时遇到问题。

这些是重要文件:

i18n / index.js

import i18next from 'i18next';

import en from './en.json';
import es from './es.json';
import it from './it.json';


const i18n = i18next.init({
  interpolation: {
    // React already does escaping
    escapeValue: false,
  },
  lng: 'en',
  // Using simple hardcoded resources for simple example
  resources: {
    en: { translation: en },
    es: { translation: es },
    it: { translation: it }
  },
});

/**
 * Translates the given string code into the current language's representation.
 * 
 * @param {string} text The string code to be translated.
 * @returns {string} The translated text.
 */
export function t(text) {
  return i18n.t(text);
}

/**
 * Changes the app's current language.
 * 
 * @param {string} language The language code, i.e: 'en', 'es', 'it', etc.
 */
export function changeLanguage(language) {
  i18n.changeLanguage(language, (err) => {
    if (err) {
      console.log('Language error: ', err);
    }
  });
}

Flags.jsx

import React, { Component } from 'react';

import { changeLanguage } from '../../../../i18n';

import './Flags.css';

export default class Flags extends Component {
  /**
   * Constructor.
   * 
   * @param {any} props The components properties. 
   */
  constructor(props) {
    super(props);
    this.changeLang = this.changeLang.bind(this);
  }
  /**
   * Changes the app's current language.
   * 
   * @param {string} language The language code, i.e: 'en', 'es' or 'it'.
   */
  changeLang(language) {
    changeLanguage(language);
    alert('language change: ' + language);
  }

  /**
   * Renders this component.
   * 
   * @returns {string} The components JSX code.
   */
  render() {
    return (
      <li role="presentation">
        <div className="flags">
          <button onClick={ () => this.changeLang('en') }>
            <span className="flag-icon flag-icon-us"></span>
          </button>
          <button onClick={ () => this.changeLang('es') }>
            <span className="flag-icon flag-icon-es"></span>
          </button>
          <button onClick={ () => this.changeLang('it') }>
            <span className="flag-icon flag-icon-it"></span>
          </button>
        </div>
      </li>
    );
  }
}

我认为更改语言是有效的,但并没有以响应方式进行,因为当我单击标志时,更改不会反映在UI中。我该怎么办?

1 个答案:

答案 0 :(得分:1)

组件未显示更新的语言,因为它不会重新呈现

正确的实现应将新的支持传递给使用翻译的组件,但似乎不是

(...要更新组件,您需要将语言作为道具传递或保持其状态,更改语言后组件将重新呈现)

所以看看使用包装器组件https://react.i18next.com/latest/translation-render-prop 或提供者或类似的https://react.i18next.com/latest/i18nextprovider 因为它看起来不像示例中那样包装组件

相关问题