gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:38:52 31 4
gpt4 key购买 nike

我正在尝试使用 react-i18next 使用包含一些 HTML 标记的翻译 json,如下所示:

// en.json
{ "welcome": "Welcome to our site, <strong>{{name}}</strong>" }

在我的 React 组件中,我希望字符串像这样呈现。

Welcome to our site, John

使用 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?

提前致谢。

最佳答案

张贴在这里是因为这是 interwebz 上的第一个搜索结果,没有一个答案适合我的情况。

我的翻译 JSON 如下所示:

"readOnlyField": "<0>{{- key}}:</0> <1>{{- value}}</1>"

我设法让它工作的唯一方法是像这样使用 Trans:

<Trans
i18nKey="readOnlyField" // the key in your JSON file
values={{ // The variables in your i18n entry from the JSON file
key: "Storage",
value: "2TB SSD",
}}
components={[<strong />, <i />]} // The component at index 0 (<strong />) will be parent of <0> ({{- key}}), and so on...
/>

所以它看起来像这样:

Storage: 2TB SSD

关于reactjs - 包含 HTML 标签的翻译的 React-i18n Trans 组件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61268001/

31 4 0