我有一个常量,它只导出数据。
Import i18n from './i18n'
export const offersList = [
{
id: 0,
itemButton: i18n.t('item1'),
title: i18n.t('title1'),
},
{
id: 0,
itemButton: 'Item 1',
title: 'Title 1',
},
{
id: 0,
itemButton: 'Item 1',
title: 'Title 1',
}
];
当我试图在键中使用t函数时,它只返回一个简单的字符串,其中包含我想要显示的键。我有像这个一样的i18n.ts文件
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
i18n
.use(Backend)
.use(initReactI18next)
.init({
fallbackLng: 'ru',
debug: true,
react: {
useSuspense: false
},
interpolation: {
escapeValue: false,
}
});
export default i18n;
所以我找到了一个解决方案,它在我的情况下有效,但也许你也有同样的解决方案。
问题是我使用了i18next 的后端模块
import Backend from 'i18next-http-backend'
在我的情况下,我不应该使用这个模块。所以i18n.js(在我的情况下是.ts(配置文件将类似于这个
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// the translations
// (tip move them in a JSON file and import them)
const resources = {
en: {
translation: {
'title': 'En test title',
},
},
ru: {
translation: {
'title': 'Ru test title',
},
}
};
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: 'en',
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false, // react already safes from xss
},
});
export default i18n;
如果您想在一个简单的js/ts文件中处理组件外的数据您可以使用t((函数。你应该在你的文件中导入你的i18next配置文件(在我的例子中是一个简单的对象数组,我导出了数据(
import i18n from '../../i18n';
const offersList = [
{title: i18n.t('title')},
{text: i18n.t('text')},
{subtitle: i18n.t('subtitle')},
]
// keep in mind, if you want to change the language with a click in-app, you should keep i18n.on a function to fire update what language was changed.
i18n.on('languageChanged', (language) => {
offersList[0].itemButton = i18n.t('title');
});
export default offersList;
尝试将简单的ts文件重构为react钩子,并在钩子内调用useTranslation()
。应该有效。