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

如何在react-i18next翻译字符串中为插入的动态变量设置粗体样式

解决方案

你之前的写法无效,是因为t函数默认返回纯字符串,传入的React元素会被序列化为普通文本,无法正常渲染样式。实现动态变量加粗需要用到react-i18next提供的<Trans>组件,它专门用于处理翻译内容中嵌入JSX元素的场景,以下是两种可行实现方案:

方案1(无需修改现有翻译文件)

  • 导入Trans组件
import { useTranslation, Trans } from 'react-i18next'
  • 调整组件渲染逻辑:
const { t } = useTranslation('payment');
const companyName = 'Probando';

<Typography>
  <Trans
    i18nKey="setup with company name"
    ns="payment"
    values={{ companyName }}
    components={{
      // 直接指定companyName变量用strong标签包裹
      companyName: <strong />
    }}
  />
</Typography>

方案2(适配多语言差异化标签位置需求)

如果不同语言版本需要加粗的内容位置不一样,可以修改翻译文件插入自定义标签占位:

  • 调整payment en.json:
{
  "setup with company name": "Please contact <b>{{ companyName }}</b> to re-edit or re-send this invitation."
}
  • 调整payment de.json:
{
  "setup with company name": "Bitte wenden Sie sich an <b>{{ companyName }}</b> um diese Einladung nochmal zu bearbeiten oder neu zu erhalten."
}
  • 组件代码:
import { useTranslation, Trans } from 'react-i18next'

const { t } = useTranslation('payment');
const companyName = 'Probando';

<Typography>
  <Trans
    i18nKey="setup with company name"
    ns="payment"
    values={{ companyName }}
    components={{ b: <strong /> }}
  />
</Typography>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:24:03