我有一个react母语应用程序,默认语言是英语.我有一个个人资料页面,用户可以在其中将语言从英语更改为另一种语言.当用户保存语言更改时,包括标题、抽屉导航名称在内的语言都应更改为用户 Select 的语言.我们如何在react native中实现此功能?

推荐答案

你可以使用这个软件包:https://github.com/AlexanderZaytsev/react-native-i18n

安装完成后,您只需定义语言环境文件,例如:

// src/i18n/locales/en.js
export default {  
  greeting: 'Hi!'
};

// src/i18n/locales/es.js
export default {  
  greeting: 'Hola!'
};

// src/i18n/locales/jp.js
export default {  
  greeting: 'Konichiwa!'
};

然后导入这些文件并设置i18n支持的配置,如下所示:

// src/i18n/index.js
import I18n from 'react-native-i18n';
import en from './locales/en';
import es from './locales/es'; 
import jp from './locales/jp';  

I18n.fallbacks = true;

I18n.translations = {
  en,
  es,
  jp,
};

export default I18n; 

最后在你的组件中使用它,比如:

import I18n from 'src/i18n';

class Demo extends React.Component {
  render () {
    return (
      <Text>{I18n.t('greeting')}</Text>
    )
  }
}

默认情况下,它将使用设备的区域设置,但如果您想覆盖该区域设置.例如,当用户拥有西班牙语区域设置的设备,但想要使用日语时,可以执行以下操作:

I18n.locale = 'jp';

无论何时调用I18n.t('greeting'),它都会呈现Konichiwa!.从现在起,你将始终需要使用I18n.t来呈现应用程序中的任何文本.

这个库的主要问题是,一旦你的应用程序增长,你不知道哪些密钥仍在使用,管理你的所有翻译非常具有挑战性,我建议你使用LinguiJS这样的工具:https://bleext.com/post/translating-your-product-into-multiple-languages

React-native相关问答推荐

ITMS—91053:缺少API声明—ReactNative

单击时更改ToucheableOpacity colored颜色 不起作用

使用react-native-reanimatedreact 导航崩溃

无法读取 @react-native-async-storage/async-storage 的未定义属性setItem

需要以前的props和state回调的静态 getDerivedStateFromProps?

react-native 签名 [AppName]Tests 需要开发团队 ios

未找到 xcode 'boost/config/user.hpp' 文件

使用像 React Navigation 这样的基于 JS 的导航解决方案优缺点?

使用离线包在 iOS 设备上运行 react-native 应用程序

使用 WSL2 运行时如何将手机连接到 expo

动画属性启动时 ReactNative ActivityIndi​​cator 不显示 false

React Native - React Navigation导航转换

运行时尚未准备好进行调试

React Native:使用选项卡动画收缩标题

react-native-webview :对于 iOS 文本太小

React-Native 元素卡在 :app:installDebug

以编程方式读取 app.json(或 exp.json)

如何在 react-native 中设置 Alert 元素的样式?

移动应用程序不需要 CORS?

如何在 react-native 中为带有图标的按钮建模