You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React i18next自定义ICU格式化器失效问题求助

问题原因及解决方案

你的问题出在自定义格式化器的注册对象错误:你把lowercase格式化器注册到了i18n的内置formatter上,但实际处理ICU语法的是i18next-icu插件的格式化器,两者不是同一个对象,所以ICU解析时不识别你定义的lowercase格式,直接输出了未解析的模板字符串。

修复步骤

需要将自定义格式化器注册到i18next-icu的实例上,而不是i18n原生的services.formatter。同时修正资源配置的结构错误,修改后的完整代码如下:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import enTranslation from "./locales/en/translation.json"
import LanguageDetector from 'i18next-browser-languagedetector';
import ICU from 'i18next-icu';

i18n
    .use(LanguageDetector)
    .use(ICU)
    .use(initReactI18next)
    .init({
        fallbackLng: 'en',
        debug: true,
        initImmediate: false,
        resources: {
            en: { translation: enTranslation } // 修正资源结构,确保翻译内容被正确读取
        },
        lng: "en",
        interpolation: {
            escapeValue: false,
        }
    });

// 获取i18next-icu的格式化器实例并注册自定义规则
const icuFormatter = i18n.services.formatter?.instance;
if (icuFormatter) {
  icuFormatter.addFormatter('lowercase', function(value) {
    return value.toLowerCase();
  });
}

export default i18n;

验证说明

修改完成后,使用<Trans i18nKey="custom-format" values={{value: "MiXtUrE"}}/>即可正确渲染出Example mixture.,自定义格式化器会正常生效。

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:40:45