2

以前我正在使用react-intl并且能够为将替换为组件的项目设置占位符,例如{br}使用<br />.

我目前在使用react-i18nexti18next-icu尝试执行操作时遇到错误:

// Using Intl format (via i18next-icu)
{
  "test": "Replace with a{br}line-break. {button}"
}
t("test", { br: <br />, button: <button>Click me!</button> });
// Outputted translated text
Replace with a[object Object]line-break. [object Object]

实际上可以使用i18next/来做到这一点i18next-icu吗?如果不是,将组件插入已翻译字符串的另一种方法是什么?

4

2 回答 2

2

您需要在 i18n.js 中像这样配置 react i18next 以支持基本标签:

import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";

i18n
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        fallbackLng: "en",
        react: {
            // https://react.i18next.com/latest/trans-component#trans-props
            transSupportBasicHtmlNodes: true,
            transKeepBasicHtmlNodesFor: ["br", "strong", "b", "i"],
        }
    });

export default i18n;

然后你可以像@jamuhl所说的那样使用组件:

const keyInTranslationJsonFile=`My text that can be <b>{{boldPlaceholder}}</b>`;
<Trans i18nKey={keyInTranslationJsonFile}>{{boldPlaceholder: "bold"}}</Trans>

我刚刚注意到不可能提醒 Trans 组件。据我所知,你不能用这个t()函数做粗体或使用任何标签。但是您至少仍然可以使用普通占位符。

像这样:

const keyInTranslationJsonFile=`You've selected the max of {{selectLimit}} elements`;
alert(
    t(keyInTranslationJsonFile, {
        selectLimit: selectLimit,
    })
);
于 2021-03-08T17:13:02.947 回答
1

https://react.i18next.com/latest/trans-component用于在您的翻译中包含反应组件(如 br、strong 等)

于 2019-03-05T12:19:46.707 回答