react-i18next: 在文本中间的 HTML 标签中插入 link

react-i18next: interpolation of link in HTML tag in the middle of the text

我正在使用 React,i18next and react-i18next。我想在文本中间插入一些带有 HTML link 的可翻译文本,这些文本是在反应中插入的,如下所示:

This is my text with <a href="{{link}}">a beautiful link</a> in the middle of the text

下面的解决方案有效,但问题是我需要在 React 中插入 link,因此它不能在标签文件中进行硬编码:

"my-label": "This is my text with <a href=\"http://google.com\">a beautiful link</a> in the middle of the text"

[...]

<Interpolate i18nKey="my-label" useDangerouslySetInnerHTML />

好像这样好多了:

"my-label": "This is my text with {{link}} in the middle of the text",
"link" "a beautiful link"

[...]

const { url } = props;
const link = <a href={url}>{t('link')}</a>

<Interpolate i18nKey="my-label" link={link} />

可能是解决方案,但是该应用程序已翻译成多种语言,翻译质量确实很重要,因此我更喜欢将整个文本放在一行中供翻译人员使用(这对于有案例的语言尤其重要)。

有什么方法可以像这样工作(或者有什么方法可以完全不同地解决它)吗?

"my-label": "This is my text with <a href=\"{{link}}\">a beautiful link</a> in the middle of the text"

[...]

const { url } = props;

<Interpolate i18nKey="my-label" useDangerouslySetInnerHTML link={url} />

<Interpolate i18nKey="my-label" useDangerouslySetInnerHTML link={url} /> 几周前添加并且确实允许插入包含 html 片段的翻译 - 请注意,如果 url 来自用户输入并包含恶意代码(xss 攻击)

,这是危险的

据我所知,这是去年添加的:https://github.com/i18next/react-i18next/pull/195/files

但是这会在默认情况下围绕每个部分包装一个跨度 before/after {{link}} 所以这可能不是你需要的......但解决方案相当简单 - 不要使用插值组件,但对 t 函数进行常规插值:

<div dangerouslySetInnerHTML={t('my-label', { link: yourURL }} />

这是 react-intlreact-i18next 的常见问题 - 这两个库对内联组件和翻译中的富文本格式的支持非常有限(我已经描述过了 更多细节)。

如果您仍处于项目的开始阶段,您可能需要考虑不同的 i18n 库 - js-lingui(免责声明:我是作者)。它是第一个(也是迄今为止唯一的)完全支持内联组件的库。

你只需写:

<Trans>See the <Link to="/more">description</Link> below.</Trans>

您的翻译人员将处理消息 See the <0>description</0> below.

唯一的代价是你需要使用额外的 babel 插件,这使得它成为可能。

我们在 react-i18next v4.4.0 中引入了一个新组件 Trans:

<Trans i18nKey="optionalKey">See the <Link to="/more">description</Link> below.</Trans>

json 将是:See the <1>description</1> below.

甚至更复杂:

<Trans i18nKey="userMessagesUnread" count={count}>
Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
</Trans>

此处记录了新功能:https://react.i18next.com/latest/trans-component

只需要使用t属性link将Trans标签添加到语言文件即可。标签之间的内容并不重要

<Trans i18nKey="cookieConsent.content" t={t}>
    x<Link to="/#privacy-policy">y</Link>z<Link to="/#legal">w</Link>
</Trans>