【问题标题】:i18next - Apply custom formattingi18next - 应用自定义格式
【发布时间】:2020-09-17 16:12:55
【问题描述】:

我有 2 个命名空间:

  • 第一个是全球性的,包含与业务相关的词汇表
  • 第二个是针对特定页面的
// global ns
{
  "amendment": "amendment"
}

// page ns
{
  "action": "Enter your $t(global:amendment) below."
}

我在 react 组件中的用例:

import React from 'react'
import { useTranslation } from 'react-i18next';

export function MyComponent() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t('amendment')}</h1>
      <p>{t('action')}</p>
    </div>
  )
}

我想使用大写转换来格式化 h1 元素中包含的文本。
实现这一目标的最佳方法是什么?

我已经考虑使用上下文并执行以下操作:

// global ns
{
  "amendment": "amendment",
  "amendment_uppercase": "Amendment"
}
import React from 'react'
import { useTranslation } from 'react-i18next';

export function MyComponent() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t('amendment', {context: 'uppercase'})}</h1>
      <p>{t('action')}</p>
    </div>
  )
}

这里的问题是我必须复制所有翻译键,而且我有很多全球词汇表。

【问题讨论】:

    标签: javascript internationalization i18next


    【解决方案1】:

    我会应用 t 方法的结果格式。

    类似:

    import React from 'react'
    import { useTranslation } from 'react-i18next';
    
    export function MyComponent() {
      const { t, i18n } = useTranslation();
    
      return (
        <div>
          <h1>{t('amendment').toUpperCase()}</h1>
          <p>{t('action')}</p>
        </div>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多