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

如何配置i18next使自定义带注释JSON自动取value属性作为翻译值

i18next适配自定义带注释翻译JSON方案

你可以根据自己的资源加载方式选择以下任意一种方案实现需求,所有方案都不需要在调用t()时额外传参:

方法1:预转换本地翻译资源(最推荐,性能最优)

在初始化i18next前先递归处理所有翻译资源,直接把叶节点的value值提取出来作为最终翻译内容:

// 递归处理工具函数
function extractValueFromResource(obj) {
  if (typeof obj === 'object' && obj !== null && 'value' in obj) {
    return obj.value
  }
  if (typeof obj === 'object' && obj !== null) {
    const processed = {}
    for (const key in obj) {
      processed[key] = extractValueFromResource(obj[key])
    }
    return processed
  }
  return obj
}

初始化时传入处理后的资源:

import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
// 导入原始翻译文件
import en from './locales/en.json'
import zh from './locales/zh.json'

i18n
  .use(initReactI18next)
  .init({
    resources: {
      en: {
        translation: extractValueFromResource(en)
      },
      zh: {
        translation: extractValueFromResource(zh)
      }
    },
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false
    }
  })

配置完成后直接调用即可得到预期结果:

t('headerbar.search.placeholder')  // 返回 'Enter your search here...'
t('welcome.heading', {name: 'Bob'}) // 返回 'Welcome, Bob!'

方法2:封装自定义t函数(适合不想改动资源加载逻辑的场景)

如果你不希望提前处理资源,也可以全局封装一层t函数,自动处理返回结果:

// 全局封装自定义翻译函数
export const t = (key, options = {}) => {
  const rawResult = i18n.t(key, { ...options, returnObjects: true })
  return typeof rawResult === 'object' && rawResult !== null && 'value' in rawResult 
    ? rawResult.value 
    : rawResult
}

后续业务代码直接引入这个封装后的t函数使用即可,用法和原生t函数完全一致。

方法3:远程加载资源适配

如果你使用i18next-http-backend动态拉取远程翻译文件,可以直接在backend的parse配置项里处理返回的JSON:

import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import Backend from 'i18next-http-backend'
// 复用方法1中的提取函数
import { extractValueFromResource } from './utils'

i18n
  .use(Backend)
  .use(initReactI18next)
  .init({
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false
    },
    backend: {
      parse: (rawData) => {
        const originJson = JSON.parse(rawData)
        return extractValueFromResource(originJson)
      }
    }
  })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 20:24:02