React-i18n Trans 组件的翻译包含 HTML 标签不起作用

IT技术 reactjs i18next react-i18next
2021-05-18 07:08:15

我正在尝试使用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 标签。

文档:在翻译中使用 for<br />和其他简单的 html 元素 (v10.4.0)

但是我对如何使用它们感到困惑,因为它们显示的示例似乎是用于替换占位符标签,例如<1>用实际标签(如<br />. 有没有办法使用 Trans 组件(或其他一些不使用的方法dangerouslySetInnerHTML)来将翻译后的字符串解释为 HTML?

提前致谢。

2个回答

是的,你做错了。

return (
  <Trans i18nKey="welcome">
    Welcome to our site, <strong>{{name}}</strong>
  </Trans>
)

您的 JSON 文件应如下所示:

"welcome": "Welcome to our site, <1>{{name}}</1>"

您使用的原因<1>是因为Trans将您的字符串分解为一个数组,所以在这种情况下它是:https : ["Welcome to our site, ", "<strong>{{name}}</strong>"] //react.i18next.com/latest/trans-component#how-to-get-the-correct-translation-string

我刚刚发布了一个我可以解决的类似问题的答案,但在React Native 中,也应该在React 中工作https : //stackoverflow.com/a/70112582/9506908

// render
<Trans i18nKey="yourTranslationKey" components={{ link: <Text onPress={() => console.log('do something')}}} /> }} />

// translationFile
{...
 "yourTranslationKey": "Please <link>Click me</link>",
...}```