javascript - 如何在 i18n-js 中使用 setLocale?
问题描述
我在我的 expo 项目中使用 i18n-js 来翻译我的应用程序。
这是我配置它的方式:
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
在我的视图中使用:
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>
);
}
该函数被调用,但文本仍然是英文,我做错了什么?
解决方案
您需要在顶级组件中设置翻译,例如 App.js。然后,您必须创建 2 个 json 文件:fr.json
并en.json
在/src/locales/
.
最后,在任何屏幕中,您都必须导入i18n
并使用该t()
函数来翻译字符串。
在 App.js 中
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"
}
}
推荐阅读
- wso2 - .NET Web 应用程序的 WSO2 管理服务
- angular - AnyChart 库应该如何与 Angular 一起使用?
- java - 创建服务bean Spring boot
- amazon-web-services - 我尝试通过 python 创建 S3 存储桶但语法无效
- javascript - 在使用数据库数据更新上下文后,React 'useContext' 挂钩不会重新渲染
- java - 如何获得 PrefixQuery 找到的词的位置?
- php - 如何给一个href以重定向到worpdress中的页面?
- python - 将多个模块从子文件夹导入到另一个文件夹
- grep - 有没有办法通过任何方法仅过滤 .png 文件?
- javascript - 我应该如何根据数组参数在函数中传递来增加 && 运算符的数量?