我正在使用react,i18next和react-i18next。我想在文本中间有一些可翻译的文本,其中有html链接在react中被插值,类似的内容:
This is my text with <a href="{{link}}">a beautiful link</a> in the middle of the text
下面的解决方案有效,但问题是我需要在react中插入链接,以便在标签文件中进行硬编码:
"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} />
with 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
这是react-intl
和react-i18next
的常见问题 - 两个LIB对内联组件和富文本格式的内部翻译中的支持非常有限(我已经在此处对其进行了描述,并提供了更多详细信息(。
如果您仍处于项目的开头,则可能需要考虑不同的I18N库-JS -Lingui(免责声明:我是作者(。这是第一个(到目前为止唯一的(库,并全力支持内联部分。
您简单地写:
<Trans>See the <Link to="/more">description</Link> below.</Trans>
您的翻译人员将与消息See the <0>description</0> below.
唯一的价格是您需要使用额外的babel插件,这使它成为可能。
您只需要使用t属性将trans标签链接到语言文件。在标签之间您拥有的并不重要
<Trans i18nKey="cookieConsent.content" t={t}>
x<Link to="/#privacy-policy">y</Link>z<Link to="/#legal">w</Link>
</Trans>
<Interpolate i18nKey="my-label" useDangerouslySetInnerHTML link={url} />
几周前添加了,并且确实允许插入包含HTML片段的翻译 - 请注意,如果URL来自用户intust并包含恶意代码(XSS攻击(
正如我所看到的,去年添加了:https://github.com/i18next/react-i18next/pull/195/files
但这将在{{link}}之前/之后的每个部分周围围绕一个跨度包裹一个跨度,以便您可能不是您需要的...但是解决方案很简单 - 请勿使用interpaly组件,而是在此处使用的常规插值t功能:
<div dangerouslySetInnerHTML={t('my-label', { link: yourURL }} />