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

React i18n不使用Trans组件如何实现字符串插值替换?

实现方案

无需使用Trans组件,直接通过翻译函数的传参能力完成插值即可,以常用的react-i18next库为例:

  1. 组件内引入useTranslation获取翻译函数t
  2. 调用t时传入第二个参数作为插值对象,key对应翻译JSON中的占位符名称
    完整代码示例:
import { useTranslation } from 'react-i18next';

function YourComponent() {
  const { t } = useTranslation();

  const fireError = (n) => {
    alert(t('percentage', { percentage: `${n}%` }));
  }

  // 其余组件逻辑
}

如果你没有使用第三方i18n库,需要自己实现插值逻辑,也可以用下面的方案:

// 你的翻译资源对象
const translations = {
  "percentage": "The value should go over {{percentage}} to be accepted"
};

// 自定义翻译函数
function translate(key, params = {}) {
  let text = translations[key] || key;
  // 替换所有{{xxx}}格式的占位符
  Object.entries(params).forEach(([param, value]) => {
    text = text.replace(new RegExp(`{{${param}}}`, 'g'), value);
  });
  return text;
}

// 调用
const fireError = (n) => {
  alert(translate('percentage', { percentage: `${n}%` }));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:15:00