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

如何在React的JS翻译文件中动态插入数值?

自定义动态翻译函数的可行性及优化方案

问题背景

在React项目中,因公司政策限制无法使用成熟的i18n工具,当前采用的翻译文件结构如下:

export const translations = {
  foo: {
    en: 'ABC',
    de: 'DEF',
  },
  bar: {
    en: 'GHI',
    de: 'JKL',
  },
  // 更多翻译项
}

调用翻译的方式为:

import { translations } from './translations';
// ...
<p>{translations['foo'][locale]}</p>

现在需要在翻译内容中动态插入数值,例如:

export const translations = {
  messages: {
    en: 'You have {{number}} new messages',
    de: 'Du hast {{number}} neue Nachrichten',
  },
  // 更多翻译项
}

希望通过类似 <p>{customTranslationFunction(translations['messages'][locale], {number: 2})}</p> 的方式实现动态替换,询问该方案是否可行,同时已编写了如下测试函数:

const translationWithNumber = (numberOfMessages: number) =>
    translations['messages'][locale].replace(
      /\{\{number\}\}/,
      String(numberOfMessages),
    );

可行性及优化建议

方案完全可行

你编写的自定义替换函数是有效的,能实现指定数值的替换需求。不过可以将其优化为通用型函数,适配更多不同的占位符和翻译项,避免为每个带占位符的翻译单独写函数:

const customTranslationFunction = (translationStr: string, params: Record<string, string | number>) => {
  return Object.entries(params).reduce((result, [key, value]) => {
    const placeholder = new RegExp(`{{${key}}}`, 'g');
    return result.replace(placeholder, String(value));
  }, translationStr);
};

使用示例

调用时只需传入目标翻译字符串和替换参数即可:

// 替换单个参数
<p>{customTranslationFunction(translations['messages'][locale], {number: 2})}</p>

// 支持多个参数的场景(如果后续有需求)
// 翻译项示例:
// greet: {
//   en: 'Hello {{name}}, you have {{count}} notifications',
//   de: 'Hallo {{name}}, du hast {{count}} Benachrichtigungen'
// }
<p>{customTranslationFunction(translations['greet'][locale], {name: 'Anna', count: 5})}</p>

额外提示

  • 如果需要处理复数等更复杂的场景,可以在通用函数基础上扩展逻辑,比如根据数值判断使用不同的翻译片段
  • 建议给占位符替换加上全局匹配(g修饰符),避免同一个占位符出现多次时只替换第一个

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:20:26