react-native - 组件渲染时 i18n 未初始化
问题描述
在我的 expo 应用程序中,我想使用 i18n-js 国际化字符串。
问题是,它是异步初始化的,组件的渲染速度更快。出于这个原因,我得到“缺少 xy 翻译”的结果。如何实现渲染前的初始化?
我发布了我的 i18n 组件。计划只是导入那个并使用它的 funktion t()。
import * as Localization from 'expo-localization';
import i18n from 'i18n-js';
i18n.translations = {
en: {
"hello": "Hello World!"
, "signin": "Sign In"
, "wrongPassword": "Wrong Password"
, "Please enter a valid email address": "Please enter a valid email address"
, "Username contains unallowed characters": "Username contains unallowed characters"
, "No Acount? Sign Up": "No Acount? Sign Up"
, "Password": "Password"
, "Password is too short. Must be greater than 6 characters": "Password is too short. Must be greater than 6 characters"
, "Passwords do not match": "Passwords do not match"
, "Email address": "Email address"
, "Enter password again":"Enter password again"
, "Password Confirm":"Password Confirm"
, "SIGN UP":"Sign Up"
, "Already Signed Up? Sign In": "Already Signed Up? Sign In"
, "You":"You"
, "Your running games":"Your running games"
, "New Game":"New Game"
, "me": "me"
},
de: {
"hello": "Hello World!"
, "signin": "Einloggen"
, "wrongPassword": "Falsches Passwort"
, "Please enter a valid email address": "Bitte benutzen Sie eine valide Email Adresse"
, "Username contains unallowed characters": "Benutzername enthält unerlaubte Zeichen"
, "No Acount? Sign Up": "Kein Konto? Registrieren!"
, "Password": "Passwort"
, "Password is too short. Must be greater than 6 characters": "Passwort zu kurz. Bitte mindestens 6 Zeichen"
, "Passwords do not match": "Passwörter stimmen nicht überein"
, "Email address": "Email Adresse"
, "Enter password again":"Passwort nochmal eingeben"
, "Password Confirm":"Passwort bestätigen"
, "SIGN UP":"Registrieren"
, "Already Signed Up? Sign In":"Bereits registriert? Einloggen!"
, "You":"Du"
, "Your running games":"Deine laufenden Spiele"
, "New Game":"Neues Spiel"
, "me": "ich"
}
};
// Set the locale once at the beginning of your app.
i18n.locale = Localization.locale;
i18n.fallbacks = true;
const t = (text) => {
return i18n.t(text);
};
export default t;
解决方案
由于我无法直接解决上述问题,我的解决方法是实现我自己的功能。就我而言,我只提供两种语言,所以很简单。如果它也能帮助其他人,我很高兴:
import * as Localization from 'expo-localization';
import en from './en.json';
import de from './de.json';
// Set the locale once at the beginning of your app.
const locale = Localization.locale.split('-')[0];
const t = (key) => {
var v = null;
if (locale == 'de') {
v = de[key];
}
if (locale == 'en' || v == null)
v = en[key]
if (v == null)
v='t('+key+')';
return v;
};
export default t;
推荐阅读
- qt - Qt Quick - 创建具有可变行高的 GridView 的正确方法是什么?
- chisel - 使用 peekpoketester 传递值时出错
- c++ - 数组/指针加法
- c++ - 无法填充结构数组
- c# - 如何让所有游戏对象检查哪些游戏对象有碰撞器,哪些游戏对象根本没有碰撞器?
- java - 即使文件中有文本,BufferedReader readline 也会读取 null
- javascript - 未调用 setState
- react-redux - 为什么 Redux 需要两次 dispatch
- python - 下载 MinIO 存储桶中的整个目录
- c# - 迭代特定扩展名的所有文件,同时避免符号链接