【发布时间】: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
.....
/>
)
我希望我很清楚这个问题,任何帮助将不胜感激。
【问题讨论】: