Dim*_*iwa 3 javascript reactjs react-native expo i18n-js
我在我的世博项目中使用 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;
}
Run Code Online (Sandbox Code Playgroud)
我将其传递给我并尝试在我的视图中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>
);
}
Run Code Online (Sandbox Code Playgroud)
该函数被调用,但文本仍然是英文,我做错了什么?
您需要在顶级组件(例如 App.js)中设置翻译。然后,您必须创建 2 个 json 文件:fr.json
和.en.json
/src/locales/
最后,在任何屏幕中,您都必须导入i18n
并使用该t()
函数来翻译字符串。
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 />
)
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
{
"home": {
"welcome": "Bienvenue",
"content": "Du contenu ici"
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13329 次 |
最近记录: |