reactjs - SO i18next React 中的反应式翻译
问题描述
我在尝试在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);
}
});
}
标志.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 中。我怎么能做到这一点?
解决方案
组件不显示更新的语言,因为它不重新渲染
正确的实现应该将新的道具传递给使用翻译的组件,但似乎它们不是
(...要更新组件,您需要将语言作为道具传递或将其保持在状态,然后在更改语言组件时重新渲染)
所以看看使用包装器组件https://react.i18next.com/latest/translation-render-prop 或提供程序或类似的https://react.i18next.com/latest/i18nextprovider 因为它看起来不像你像示例中一样包装您的组件
推荐阅读
- sql - 在 SQL Server 中将行值转换为列
- c# - 简单的条件断点在 Visual Studio 2017 中引发错误
- python - 编码分类变量,如“状态名称”
- php - 如何使用 http_client 测试受 lexik_jwt_authentication 保护的 API?
- java - 具体实现openGL和LWJGL中的局部旋转
- python - Django不显示两个DetailView
- taleo-connect-client - 如何在 Taleo Connect 客户端的投影脚本中编写“If-condition”
- java - 将@Transactional 和调用两个或多个表的逻辑放在哪里?
- ios - SwiftUI:如何将 CoreData 与动态过滤器相加?
- xamarin.forms - Xamarin.Forms 每个平台和设备的不同视图