我正在尝试将react-i18nnext
与包含一些HTML标记的翻译json一起使用,例如:
react-i18nnext
在我的React组件中,我希望字符串以这种方式呈现。
欢迎来到我们的网站,John
通常使用// en.json
{ "welcome": "Welcome to our site, <strong>{{name}}</strong>" }
函数按原样打印字符串,而不像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>
。我在文档中读到,您可以使用称为Trans组件的东西进行带有HTML标签的翻译。
文档:dangerouslySetInnerHTML
但是我对如何使用它们感到困惑,因为它们显示的示例似乎是用诸如Using for <br />
and other simple html elements in translations (v10.4.0)的实际标签替换诸如<br />
的占位符标签。是否可以使用Trans组件(或其他一些不使用<1>
的方法)来将翻译后的字符串解释为HTML?
提前感谢。
是,您做错了。
<br />
并且您的JSON文件应如下所示:
dangerouslySetInnerHTML
您使用return (
<Trans i18nKey="welcome">
Welcome to our site, <strong>{{name}}</strong>
</Trans>
)
的原因是因为"welcome": "Welcome to our site, <1>{{name}}</1>"
将您的字符串分成一个数组,因此在这种情况下为:<1>
Trans