反义词中的i18next反应性翻译

问题描述 投票:0回答:1

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

这些是重要的文件:

国际化/ 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中。我怎么能做到这一点?

reactjs internationalization translation reactive i18next
1个回答
1
投票

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

正确的实现应该将新的道具传递给使用翻译的组件但似乎不是

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

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

© www.soinside.com 2019 - 2024. All rights reserved.