如何在Expo多页面中使用i18n-js?解决调用报错问题
解决i18n-js在Expo子页面调用
I18n.t报错的问题 1. 修正i18n实例的导入与使用方式
i18n-js v4.x 采用实例化方式使用,而非直接调用类的静态方法I18n.t。请单独创建配置文件并导出实例:
- 在
app目录下新建i18n.ts文件,内容如下:
import { I18n } from 'i18n-js'; import * as Localization from 'expo-localization'; // 解决make-plural报错,需先安装对应依赖 import '@formatjs/intl-pluralrules/polyfill'; import '@formatjs/intl-pluralrules/locale-data/en'; import '@formatjs/intl-pluralrules/locale-data/zh'; // 多语言翻译文本 const translations = { en: { welcome: 'Welcome' }, zh: { welcome: '欢迎' }, }; // 创建i18n实例并配置 const i18n = new I18n(translations); i18n.locale = Localization.locale; i18n.enableFallback = true; export default i18n;
- 在所有需要使用翻译的页面统一导入这个实例:
_layout.tsx中:
import i18n from './i18n'; // 使用时:{i18n.t('welcome')}(tabs)/home/main.tsx中:
import i18n from '../../i18n'; // 使用时:{i18n.t('welcome')}
2. 修复JSX语法错误
你之前写的<I18n.t('welcome')>是错误语法,JSX中插入表达式需要用**花括号{}**包裹,而非尖括号。正确写法示例:
<Text>{i18n.t('welcome')}</Text>
3. 解决make-plural依赖报错
运行以下命令安装缺失的依赖:
npm install @formatjs/intl-pluralrules # 或 yarn add @formatjs/intl-pluralrules
之后在i18n.ts中导入对应的polyfill和语言数据(已包含在上面的配置文件中)。
内容的提问来源于stack exchange,提问作者Yücel
相关产品推荐
相关产品推荐

