【问题标题】:bootstrap-switch-button-react :How to updated onLabel and offLabel values to different language when language is changedbootstrap-switch-button-react :更改语言时如何将标签和关闭标签值更新为不同的语言
【发布时间】:2021-10-16 07:15:51
【问题描述】:

我正在使用“bootsrap-switch-button-react”包进行 ON/OFF 开关。当语言更改为不同的语言时,标签 ON 和 OFF 不会更新。但是,如果访问了其他链接并返回到同一页面,则 ON 和 OFF 的语言会发生变化。

下面是我更新语言和使用开关的示例代码部分:

从 i18n 声明翻译:

const { t, i18n } = useTranslation();

定义 useState :

const [offlabel, setOffLabel] = useState(t("off"));

这里,在t("off")中,off是key,如果选择英语,则值为OFF,如果选择德语,则值为AUS。

触发语言更改事件:

i18n.on('languageChanged', function(lng) {
     setOffLabel(t("off")); //sets the state of useState when language is changed. 
     console.log("language changed to : ", lng); // It works fine
}

在return语句中:

return (
     <BootstrapSwitchButton 
          onlabel="Test" //static on label
          offlabel={offLabel} // IT IS NOT UPDATING ON LANGUAGE CHANGED
          checked={...} //these properties are working fine
          .....
     />

下面是整个代码,(如果有人对上面的代码感到困惑):

import React, { useState } from 'react';
import BootstrapSwitchButton from "bootstrap-switch-button-react";
import { useTranslation } from 'react-i18next';

export default function SwitchIO() {
     const { t, i18n } = useTranslation();
     const [offlabel, setOffLabel] = useState(t("off"));
     i18n.on('languageChanged', function(lng) {
          setOffLabel(t("off")); //sets the state of useState when language is changed. 
          console.log("language changed to : ", lng); // It works fine
     }

     return (
          <BootstrapSwitchButton 
               onlabel="Test" //static on label
               offlabel={offLabel} // IT IS NOT UPDATING ON LANGUAGE CHANGED
               checked={...} //these properties are working fine
               .....
          />
     )

我希望我很清楚这个问题,任何帮助将不胜感激。

【问题讨论】:

    标签: reactjs i18next


    【解决方案1】:

    我认为您不需要useState 来控制翻译。

    t('key) 负责自动选择翻译。只需摆脱 useState 并简单地

     <BootstrapSwitchButton 
                   onlabel="Test" //static on label
                   offlabel={t('off')} // This will by itself take care of translation
                   checked={...} //these properties are working fine
                   ...../>
    

    【讨论】:

    • 其实我也试过了,它并没有更新语言更改。但是,在这两种情况下,(就像你建议的那样,就像我对 useState 所做的那样),一旦我访问其他链接并返回此页面,语言就会改变。无论如何,我深入研究了 BootstrapSwitchButton 中使用的类,进行了一些更改并设计了我自己的自定义开关按钮。现在它按预期工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2022-01-13
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    相关资源
    最近更新 更多