【发布时间】:2020-04-17 09:14:34
【问题描述】:
我正在尝试将 react-i18next 与包含一些 HTML 标记的翻译 json 一起使用,如下所示:
// en.json
{ "welcome": "Welcome to our site, <strong>{{name}}</strong>" }
在我的 React 组件中,我希望字符串像这样呈现。
欢迎来到我们的网站,约翰
使用 useTranslation 函数通常会按字面意思打印字符串,而不会将其解释为 HTML,例如 Welcome to our site, <strong>John</strong>。
import React from 'react'
import { useTranslation } from 'react-i18next'
const App = () => {
const { t } = useTranslation()
return(
<div>{t('welcome', { name: 'John' })}</div>
)
}
我将它替换为dangerouslySetInnerHTML,它被正确渲染了。
<div dangerouslySetInnerHTML={{ __html: t('welcome', { name: 'John' }) }}></div>
但是,如果可能,我想避免使用dangerouslySetInnerHTML。我在文档中读到,您可以使用称为 Trans 组件的东西来翻译 HTML 标签。
文档:Using for <br /> and other simple html elements in translations (v10.4.0)
但我对如何使用它们感到困惑,因为它们显示的示例似乎是用于将 <1> 等占位符标签替换为 <br /> 等实际标签。有没有办法使用 Trans 组件(或其他不使用 dangerouslySetInnerHTML 的方法)来将翻译后的字符串解释为 HTML?
提前致谢。
【问题讨论】:
标签: reactjs i18next react-i18next