如何在@ shopify / react-i18n中更改语言时重新渲染页面?



翻译不随语言变化而变化。我使用MobX来存储语言的状态。更改语言将更改I18nContext中的区域设置。提供程序,但页面上的文本不会更改。

我的钩。

import {useI18n} from "@shopify/react-i18n";
import enTrans from "../../translate/en.json";
import frTrans from "../../translate/fr.json";
export const UseI18nHook = () => {
console.log('hook1');
return useI18n({
id: 'App',
fallback: 'fr',
translations(locale) {
return locale === "en" ? enTrans : frTrans;
},
})};

我的翻译提供者

import React from "react";
import {inject, observer} from "mobx-react";
import {I18nContext, I18nManager} from '@shopify/react-i18n';
const TranslateWrapper = inject(stores => ({
activeEnglish: stores.LocalizeStore.activeEnglish
}))(observer(({activeEnglish, children}) => {
return(
<I18nContext.Provider value={new I18nManager({
locale: activeEnglish ? 'en' : 'fr',
onError(error) {
console.log(error);
},
})}>
{children}
</I18nContext.Provider>
)
}));
export default TranslateWrapper;

在第i页使用const [i18n] = UseI18nHook();i18n.translate('App.InstallPage.installTitle')

我将实现它的方式如下:首先,我将使用自定义翻译钩子为我处理所有逻辑

import * as translations from "./Translations";
import { useEffect } from "react";
export default function useTranslation() {
const [language, setLanguage] = useState("ar");
const [fallbackLanguage, setFallbackLanguage] = useState("en");
//this is optional if the language is rtl
useEffect(() => {
document.documentElement.dir = language === "ar" ? "rtl" : "ltr";
}, [language]);
const translate = (key) => {
const keys = key.split(".");
return (
getNestedTranslation(language, keys) ?? //return the value of the key in the selected language
getNestedTranslation(fallbackLanguage, keys) ?? //return the value of the key in fallback language if there is no translation found in the main langrage
key // return the key itself if there is no translation found in the fallback language
);
};
return {
language,
setLanguage,
fallbackLanguage,
setFallbackLanguage,
t: translate,
};
}
function getNestedTranslation(language, keys) {
return keys.reduce((obj, key) => {
return obj?.[key];
}, translations[language]);
}

则有一个名为Translations的文件夹,其中包含index.js

export * as en from "./en.json";
export * as ar from "./ar.json";
//any other languages

和包含翻译

的JSON文件en.json:

"hello":"Welcome"

ar.json:

"hello": "مرحبا"

在第1页使用const {t} = useTranslation();和t("你好")

你也可以像这样嵌套键

"months": [
"feb",
"jan",
"mar"
]

t("months.1")(将返回feb) 要更改语言的组件中的执行以下操作,它应该呈现:

cosnt {setLanguage}=useTranslation();
const handleLangChange=(lang)=>{
setLanguage(lang);
}

相关内容

  • 没有找到相关文章

最新更新