【问题标题】:i18next in React Native: import {t} doesn't work (works in React Web)React Native 中的 i18next:import {t} 不起作用(在 React Web 中有效)
【发布时间】:2019-01-09 04:08:45
【问题描述】:

以下代码在正常的 React 项目中工作(我使用的是打字稿,如果重要的话):

import {t} from "i18next";

const translation = t('WelcomeMessage');

同样的代码在 React Native 项目中不起作用,会报错:

import i18n, {t} from "i18next";

const translation1 = i18n.t('WelcomeMessage');   //works ok
const translation = t('WelcomeMessage'); //ERROR: (0, _i18next.t) is not a function

为什么t('WelcomeMessage') 在 RNative 中不起作用?是否与 i18next 在 typedefinitions (export = i18next;) 中的导出方式有关?

【问题讨论】:

  • react-i18next 不是一个选项吗?
  • 我只是不需要它。我实际上可以在任何地方使用i18n.t('SomeString'),我只是好奇为什么它不起作用
  • 我的意思是,我很好奇为什么 t('WelcomeMessage') 在 RNative 中不起作用
  • 应该和metro bundler有关。

标签: reactjs typescript react-native i18next


【解决方案1】:

您可以使用i18n-js 实现此功能 https://github.com/fnando/i18n-js/releases

创建一个.js 文件。

import i18n from 'i18n-js';

import en from '../translations/en.json';
import ar from '../translations/ar.json';

i18n.fallbacks = true;
i18n.translations = { en, ar };

export default i18n;

在组件类中调用这个 i18n.js 文件

import i18n from './i18n'
class Test extends Component {

   render(){
     return(
        <Text>i18n.t('sample')</Text>
     )
   }

}

【讨论】:

  • 抱歉,我没有从您的回答中受益。 i18n.t('sample') 已经为我工作了。 t('sample')(没有 i18n.)在 React Native 中不起作用。在您的示例中,您最后使用了i18n.t('sample'),这已经对我有用
猜你喜欢
  • 2022-10-23
  • 1970-01-01
  • 2022-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 2018-05-01
  • 2020-06-04
相关资源
最近更新 更多