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

react-i18next教程:如何为emailAddress变量设置样式(加粗或加className)

给react-i18next中的变量添加样式的两种方法

你可以通过以下两种方式给emailAddress变量设置加粗样式或添加className:

方法1:插值传递带样式的JSX元素

直接将变量包裹在带样式的HTML标签中,作为插值参数传给t函数即可。

代码示例

import { useTranslation } from "react-i18next";

const { t } = useTranslation("");
const emailAddress = "email@email.com";

// 方式A:内联样式设置加粗
const styledEmail = <span style={{ fontWeight: "bold" }}>{emailAddress}</span>;

// 方式B:添加自定义className(需提前在样式文件中定义.email-bold类)
// const styledEmail = <span className="email-bold">{emailAddress}</span>;

return (
  <div>
    {t("logoutCopy", { emailAddress: styledEmail })}
  </div>
);

对应翻译文件配置

确保你的翻译文案(比如en.json或zh.json)中logoutCopy的占位符正确:

{
  "logoutCopy": "请确认退出账号,如有问题请联系:{{emailAddress}}"
}

方法2:使用Trans组件(适合复杂文案场景)

如果文案结构更复杂,推荐用react-i18next提供的Trans组件,它能更灵活地处理带样式的文本片段。

代码示例

import { Trans, useTranslation } from "react-i18next";

const { t } = useTranslation("");
const emailAddress = "email@email.com";

return (
  <div>
    <Trans i18nKey="logoutCopy">
      请确认退出账号,如有问题请联系:<strong>{{emailAddress}}</strong>
    </Trans>
  </div>
);

对应翻译文件配置

Trans组件会自动将标签转换为占位符,翻译文案中需要对应使用标签索引(比如<1>对应代码中的<strong>):

{
  "logoutCopy": "请确认退出账号,如有问题请联系:<1>{{emailAddress}}</1>"
}

注意:如果需要添加className,只需把<strong>换成<span className="email-bold">,翻译文案中对应修改为<1>{{emailAddress}}</1>即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:45:45