首页 > 解决方案 > bootstrap-switch-button-react :更改语言时如何将 onLabel 和 offLabel 值更新为不同的语言

问题描述

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

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

从 i18n 声明翻译:

const { t, i18n } = useTranslation();

定义 useState :

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

这里,在 t("off") 中,off 是键,如果选择英语,则值为 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 (
     <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
               .....
          />
     )

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

标签: reactjsi18next

解决方案


我认为您不需要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
               ...../>

推荐阅读