问题描述
我在我的 expo 项目中使用 i18n-js 来翻译我的应用程序.
I am using i18n-js within my expo project to translate my app.
这是我的配置方式:
import React from 'react';
import * as Localization from 'expo-localization';
import i18n from 'i18n-js';
export default function configureI18n(translations) {
i18n.fallbacks = true;
i18n.translations = translations;
i18n.locale = Localization.locale;
const [locale, setLocale] = React.useState(Localization.locale);
const localizationContext = React.useMemo(() => ({
t: (scope, options) => i18n.t(scope, { locale, ...options }),
locale,
setLocale,
}), [locale]);
return localizationContext;
}
我将它传递给我的 AppContext
并尝试在我的视图中使用 setLocale
:
I pass this to my AppContext
and try to use setLocale
within my view:
function HomeView(props) {
const { locale, setLocale } = useContext(AppContext);
return (
<View>
<Button
style={{ marginTop: 4 }}
icon="translate"
mode="contained"
title="toggle navigation"
onPress={() => setLocale(locale.includes('en') ? 'fr' : 'en')}
>
{locale.includes('en') ? 'FR' : 'EN'}
</Button>
</View>
);
}
调用了函数,但文字还是英文,我做错了什么?
The function is called, but the text is still in english, what am I doing wrong ?
推荐答案
您需要在顶级组件中设置翻译,例如 App.js.然后,您必须在 /src/locales/
中创建 2 个 json 文件:fr.json
和 en.json
.
You need to setup the translation in your top level component, like App.js. Then, you have to create 2 json files: fr.json
and en.json
in /src/locales/
.
最后,在任何屏幕中,您必须导入 i18n
并使用 t()
函数来翻译字符串.
Finally, in any screen, you have to import i18n
and use the t()
function to translate strings.
import React, { useEffect, useState } from 'react'
import { loadLocale } from './locales/i18n'
export default function App() {
const [theme, setTheme] = useState(null)
useEffect(() => {
init()
}, [])
const init = async () => {
await loadLocale()
}
return (
<AppContainer />
)
}
在 i18n.js 中
import * as Localization from 'expo-localization'
import i18n from 'i18n-js'
i18n.defaultLocale = 'fr'
i18n.locale = 'fr'
i18n.fallbacks = true
export const loadLocale = async () => {
for (const locale of Localization.locales) {
if (i18n.translations[locale.languageCode] !== null) {
i18n.locale = locale.languageCode
switch (locale.languageCode) {
case 'en':
import('./en.json').then(en => {
i18n.translations = { en }
})
break
default:
case 'fr':
import('./fr.json').then(fr => {
i18n.translations = { fr }
})
break
}
break
}
}
}
export default i18n
在 HomeView.js 中
import React from 'react'
import i18n from '../locales/i18n'
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1 }}>
<Text>{i18n.t('home.welcome')}</Text>
<Text>{i18n.t('home.content')}</Text>
</View>
)
}
export default HomeView
在 fr.json 中
{
"home": {
"welcome": "Bienvenue",
"content": "Du contenu ici"
}
}
这篇关于如何在 i18n-js 中使用 setLocale?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!