【问题标题】:react-i18next and replacing placeholder keys with componentsreact-i18next 并用组件替换占位符键
【发布时间】:2019-07-26 19:14:38
【问题描述】:

以前我使用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 来做到这一点吗?如果不是,将组件插入已翻译字符串的另一种方法是什么?

【问题讨论】:

    标签: reactjs i18next react-intl react-i18next


    【解决方案1】:

    https://react.i18next.com/latest/trans-component 是否可以在您的翻译中包含 React 组件(例如 br、strong、...)

    【讨论】:

    • 是的,我看到了,但是它不能直接从我现有的 ICU 翻译中移植,也不是完全有帮助的。让非技术翻译人员使用&lt;0&gt;&lt;/0&gt; 标记&lt;br /&gt; 比使用&lt;br /&gt;{br} 更难。
    • 由于v10.4.0,您可以使用transKeepBasicHtmlNodesFor 选项在翻译字符串中插入基本的HTML 元素,例如&lt;br /&gt;;不需要&lt;0&gt;&lt;/0&gt;
    【解决方案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,
        })
    );
    

    【讨论】:

      猜你喜欢
      • 2016-12-16
      • 2017-09-11
      • 2013-01-24
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2022-11-25
      • 2017-10-20
      相关资源
      最近更新 更多