【问题标题】:i18next-react and custom formati18next-react 和自定义格式
【发布时间】:2021-03-18 08:06:45
【问题描述】:

我确实使用 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;
      },
    },
    ...
  },

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

import i18next from 'i18next';
i18next.format('edit', 'capitalize'),

它按预期工作......单词编辑变成大写字母。

但是,我如何在自己的翻译中使用它:t('edit') 我想知道是否有办法使用 react-i18next 而不是 i18next 包调用格式化

如果我尝试使用:t('{{edit, capitalize}}'),,则会收到以下错误:

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

【问题讨论】:

    标签: reactjs react-i18next


    【解决方案1】:

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

    TLDR;第二个,可能更好!

    第一种解决方案

    语言文件

    在我的 common.js 中,我添加了某种 Meta-Formater 字符串,如下所示:

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

    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;
          },
        },
        ...
      },
    

    如何使用

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

    t('common:capitalize', { value: t('common:edit') })
    

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

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

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

    您不需要在 common.js 中定义这样的“Meta-Formater”,只需在上一主题中描述的i18n.js config

    然后在您的组件中,您需要额外导入 i18next 并像这样使用它:

    i18next.format(t('common:settings'), 'capitalize'),
    

    在我看来,这个解决方案是更干净的解决方案,但唯一的缺点是您必须添加一个额外的导入:

    【讨论】:

      【解决方案2】:

      你应该定义一个自定义函数;让 changeCase 成为那个函数

      const changeCase = (str, isLower = false) =>
        isLower ? str.toLowerCase() : str.toUpperCase() // you can extend this function to suit your needs
      

      在您的翻译中,您可以这样做:

      changeCase(t('edit')) // here it will uppercase the whole string
      changeCase(t('edit'), true) // will lowercase the whole string
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-19
        • 2023-03-22
        • 1970-01-01
        • 2021-01-06
        • 1970-01-01
        • 1970-01-01
        • 2021-08-05
        相关资源
        最近更新 更多