簡體   English   中英

react-i18next:在文本中間插入 HTML 標簽中的鏈接

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

我正在使用 react, i18nextreact-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} />

在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-intlreact-i18next的常見問題-兩個庫對內聯組件和翻譯中的RTF格式的支持都非常有限(我已經在這里進行了詳細介紹)。

如果您仍處於項目的開始,則可能需要考慮使用其他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>u
</Trans>

<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 }} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM