ree*_*ces 6 i18next reactjs react-i18next
我正在尝试使用react-i18next包含一些 HTML 标签的翻译 json,如下所示:
// en.json
{ "welcome": "Welcome to our site, <strong>{{name}}</strong>" }
Run Code Online (Sandbox Code Playgroud)
在我的 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>
)
}
Run Code Online (Sandbox Code Playgroud)
我将其替换为dangerouslySetInnerHTML并且它已正确呈现。
<div dangerouslySetInnerHTML={{ __html: t('welcome', { name: 'John' }) }}></div>
Run Code Online (Sandbox Code Playgroud)
但是,如果可能的话,我想避免使用dangerouslySetInnerHTML。我在文档中读到,您可以使用称为 Trans 组件的东西来进行 HTML 标签的翻译。
文档:在翻译中使用 for<br />和其他简单的 html 元素 (v10.4.0)
但我对如何使用它们感到困惑,因为它们显示的示例似乎是用于替换占位符标签,例如<1>替换为<br />. 有没有办法使用 Trans 组件(或其他不使用 Trans 组件的方法dangerouslySetInnerHTML)将翻译后的字符串解释为 HTML?
提前致谢。
Fer*_*Paz 16
发布在这里是因为这是 interwebz 上的第一个搜索结果,并且没有一个答案适合我的情况。
我的翻译 JSON 如下所示:
"readOnlyField": "<0>{{- key}}:</0> <1>{{- value}}</1>"
Run Code Online (Sandbox Code Playgroud)
我设法让它工作的唯一方法是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...
/>
Run Code Online (Sandbox Code Playgroud)
所以它看起来像这样:
存储: 2TB SSD
编辑:您还可以将组件声明为地图,如下所示:
"fullName": "<primary>{{- lastName}}:</primary>, <secondary>{{- firstName}}</secondary>"
Run Code Online (Sandbox Code Playgroud)
<Trans
i18nKey="fullName"
values={{
lastName: "Doe",
firstName: "John",
}}
components={{
primary: <strong />,
secondary: <i />
}}
/>
Run Code Online (Sandbox Code Playgroud)
是的,你做错了。
return (
<Trans i18nKey="welcome">
Welcome to our site, <strong>{{name}}</strong>
</Trans>
)
Run Code Online (Sandbox Code Playgroud)
您的 JSON 文件应如下所示:
"welcome": "Welcome to our site, <1>{{name}}</1>"
Run Code Online (Sandbox Code Playgroud)
您使用的原因<1>是因为Trans将字符串分解为数组,所以在本例中它是: https: ["Welcome to our site, ", "<strong>{{name}}</strong>"]
//react.i18next.com/latest/trans-component#how-to-get-the- Correct-translation-string
| 归档时间: |
|
| 查看次数: |
23310 次 |
| 最近记录: |