react-i18next:在文本中间插入HTML标记中的链接

knu*_*hol 7 javascript i18next reactjs react-i18next

我正在使用react,i18nextreact-i18next。我想在文本中间插入一些带有HTML链接的可翻译文本,以进行插值,例如:

This is my text with <a href="{{link}}">a beautiful link</a> in the middle of the text
Run Code Online (Sandbox Code Playgroud)

下面的解决方案有效,但是问题是我需要在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 />
Run Code Online (Sandbox Code Playgroud)

看来这要好得多:

"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} />
Run Code Online (Sandbox Code Playgroud)

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

有什么办法可以使像这样的东西工作(或者有什么办法可以完全不同地解决它)?

"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} />
Run Code Online (Sandbox Code Playgroud)

jam*_*uhl 9

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

<Trans i18nKey="optionalKey">See the <Link to="/more">description</Link> below.</Trans>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

  • 感谢您的回答。我可能会误解,但这是否意味着 Trans 中的文本需要与 JSON 保持同步?如果是这样,它似乎不太方便,因为它不再充当不可变的密钥。 (3认同)
  • 像文档中所示的那样替换React节点-&gt;可以轻松完成翻译,同时保持节点按预期运行...只需看一下文档或示例:https://github.com/i18next/react- i18next / tree / master / example / react_withHOC (2认同)

Eug*_*yeu 6

由于这里没有人谈论如何将文本与链接放在JSON 中,所以我将向您展示如何

JSON:

json_key: "text <0>link</0> text"

反应:

<Trans
    i18nKey="json_key"
    components={[<Link to="/" />]}
/>
Run Code Online (Sandbox Code Playgroud)


Tom*_*ich 5

这是react-intland的常见问题react-i18next- 两个库对内联组件和翻译内部的富文本格式的支持都非常有限(我已经在此处详细描述了它)。

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

你只需写:

<Trans>See the <Link to="/more">description</Link> below.</Trans>
Run Code Online (Sandbox Code Playgroud)

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

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

  • 简,没有理由在这里粗鲁。我们都是 i18n 库的作者,我们的观点略有不同。您提出的所有观点都只是主观意见。ICU MessageFormat 是我决定实施的标准格式,由用户决定他们想要使用哪种格式。OP问了一个问题,这个问题的解决方案在react-i18next中并不容易,所以我提出了一个替代解决方案。不想劫持这个问题,但这正是我花空闲时间构建替代库的原因。 (11认同)