【问题标题】:react-i18-next use t('title') function in a simple file outside of componentsreact-i18next 在组件外的简单文件中使用 t('title') 函数
【发布时间】:2020-07-20 20:04:44
【问题描述】:

我有一个只导出数据的常量。

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',
  }
];

当我尝试在 key 中使用 t 函数时,它只返回一个简单的字符串,其中包含我想要显示的 key。 我有这样的 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;

【问题讨论】:

  • 你怎么打电话给t()
  • itemButton: i18n.t('item1')
  • 对不起,我错过了。另一个问题 - 为什么不在组件中而不是外部进行翻译?类似offersList.map(o => <Button>{i18n.t(o.itemButton)}</Button>)`?
  • 嗯不知道,会考虑的,但我想无论如何我都需要在外面使用它,因为这只是示例,真正的数组要大得多。但我会尝试
  • 也许你会在这里找到答案:stackoverflow.com/questions/44518857/…

标签: reactjs react-i18next


【解决方案1】:

所以我找到了一个解决方案,它适用于我的情况,但也许你也有同样的情况。

问题是我使用了 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;

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多