如何在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
相关产品推荐
相关产品推荐

