i18next-react 和自定义格式

sut*_*her 2 reactjs react-i18next

我确实使用 i18next-react 并尝试进行格式化。所以我在初始化格式中进行了这样的设置:

i18n.use(initReactI18next).init(
  {
    ...
    interpolation: {
      escapeValue: false,
      // eslint-disable-next-line no-unused-vars
      format: function (value, format, lng) {
        if (format === 'uppercase') return value.toUpperCase();
        if (format === 'lowercase') return value.toLowerCase();
        if (format === 'capitalize') return `${value.substr(0, 1).toUpperCase()}${value.substr(1)}`;
        return value;
      },
    },
    ...
  },
Run Code Online (Sandbox Code Playgroud)

如果我在我的反应组件中这样做:

import i18next from 'i18next';
i18next.format('edit', 'capitalize'),
Run Code Online (Sandbox Code Playgroud)

它的工作原理与预期一致...单词 edit 变为大写字母。

但是,我如何将它与我自己的翻译一起使用:t('edit') 我想知道是否有一种方法可以使用react-i18next而不是i18next包来调用格式化

如果我尝试使用:t('{{edit, capitalize}}'),,我收到此错误: 在此输入图像描述

我尝试的至少是在我的 t()-Method 中决定在该字符串上使用给定的格式。

sut*_*her 6

好的,我找到了两个解决方案。

太长了;第二个,可能是更好的一个!

第一个解决方案

语言文件

在我的 common.js 中,我添加了某种类似Meta-Formater这样的字符串:

{
  "uppercase": "{{value, uppercase}}",
  "capitalize": "{{value, capitalize}}",
  "lowercase": "{{value, lowercase}}",
}

Run Code Online (Sandbox Code Playgroud)

i18n.js 配置

我在配置中的自定义格式如下所示:

i18n.use(initReactI18next).init(
  {
    ...
    interpolation: {
      escapeValue: false,
      // eslint-disable-next-line no-unused-vars
      format: function (value, format, lng) {
        if (format === 'uppercase') return value.toUpperCase();
        if (format === 'lowercase') return value.toLowerCase();
        if (format === 'capitalize') return `${value.substr(0, 1).toUpperCase()}${value.substr(1)}`;
        return value;
      },
    },
    ...
  },
Run Code Online (Sandbox Code Playgroud)

如何使用

在我的组件中我这样使用它:

t('common:capitalize', { value: t('common:edit') })
Run Code Online (Sandbox Code Playgroud)

它的作用:我使用在 common.js 中声明的键来格式化作为参数粘贴到其中的任何值value

在我的组件中,我粘贴了仍翻译后的值common:edit。对于 DE 来说是bearbeiten,现在将大写common:capitalize

第二个解决方案(更好的一个?!?)

您不需要在 common.js 中定义此类“Meta-Formater”,只需定义i18n.js config上一主题中描述的即可。

然后在您的组件中,您需要额外导入i18next并使用它,如下所示:

i18next.format(t('common:settings'), 'capitalize'),
Run Code Online (Sandbox Code Playgroud)

在我看来,此解决方案是更干净的解决方案,但唯一的缺点是您必须添加额外的导入: 在此输入图像描述