reactjs - 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
.....
/>
)
我希望我清楚这个问题,任何帮助将不胜感激。
解决方案
我认为您不需要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
...../>
推荐阅读
- java - (Swift) JWE 使用 RSAES-OAEP 和 AES GCM
- google-cloud-platform - 到 Cloud Run 的 Google API Gateway 引发 401 错误
- ssh - 使用代理服务器将 X2GO 配置转换为 ssh 配置文件
- flutter - 如何在颤动中为图标按钮添加标签
- android - 为什么我的 RecyclerVIewSwipeDecorator 库没有被导入?
- html - 移动响应 css 不与桌面 css 重叠
- swift - 以编程方式在 Swift 中创建背景渐变
- mysql - MYSQL GROUP BY 不能处理 1 年的数据
- r - R 数据操作
- c# - 鼠标轻弹会加快应用程序 UI (WinForms) 的速度吗?