我正在使用react,i18next和react-i18next。我想要一些可翻译的文本,其中文本中间带有 HTML 链接,该链接是在 React 中插入的,如下所示:
This is my text with <a href="{{link}}">a beautiful link</a> in the middle of the text
下面的解决方案有效,但问题是我需要在反应中插入链接,这样它就不能在标签文件中硬编码:
"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} />
在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>
这是
react-intl
和 react-i18next
的常见问题 - 这两个库对内联组件和翻译内的富文本格式的支持非常有限(我已经在 here 描述了更多细节)。
如果您仍处于项目的开始阶段,您可能需要考虑不同的 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>
由于这里没有人讨论如何将带有链接的文本仅放入 JSON 中我将向您展示如何
JSON:
json_key: "text <0>link</0> text"
反应:
<Trans
i18nKey="json_key"
components={[<Link to="/" />]}
/>
<Interpolate i18nKey="my-label" useDangerouslySetInnerHTML link={url} />
几周前添加的,并且确实允许插入包含 html 片段的此类翻译 - 请注意,如果 url 来自用户输入并包含恶意代码(xss 攻击),这很危险
据我所知,这是去年添加的:https://github.com/i18next/react-i18next/pull/195/files
但这将默认在 {{link}} 之前/之后的每个部分包裹一个跨度,因此这可能不是您需要的......但解决方案相当简单 - 不要使用插值组件,而是在 t 函数上使用常规插值:
<div dangerouslySetInnerHTML={t('my-label', { link: yourURL }} />