react- native国际化

i18next 和 react-i18next 是用于实现国际化(i18n)的库。它们结合起来为 React 应用程序提供了一个强大的多语言支持解决方案。

安装:

npm install i18next  react-i18next

配置en.json


{
    "hello": "hello",
    "world": "world"
}

配置zhC.json

{
	"hello":"你好",
    "world": "世界"
}

配置languages.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// 语言包
import en from './en.json'
import zh from './zhCN.json'

const resources = {
    en: {
        translation: en
    },
    zh: {
        translation: zh
    }
}

i18n
    .use(initReactI18next)
    .init({
        compatibilityJSON: 'v3', // 对安卓进行兼容
        resources,
        fallbackLng: 'zh', // 默认语言,也是设置语言时设置了不存在的语言时使用的
        interpolation: {
            escapeValue: false
        }
    }, (err) => {
        // 錯誤
        if (err) throw err;
        // 这里放多一层函数是为了方便之后切换语言的同时做一些其他的统一处理
        i18n.setLocalLanguage = function (value) {
            // 設置項目文本的語言
            this.changeLanguage(value);
            // 做点别的,比如同时切换别的插件的语言
        }
        // 初始化
        i18n.setLocalLanguage(i18n.language);
    });


export default i18n;

在根目录index.js引入 languages.js

类组件中使用


import React, { Component } from "react";
import { View, Text, Button } from "react-native";
import { withTranslation } from 'react-i18next';

class HomeScreen extends Component {
  render() {
    const { t, i18n } = this.props;

    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>当前语言包:{i18n.language}</Text>
        <Text>{i18n.t("请输入您的手机号")}{i18n.t("")}</Text>
        <Button title='切换为中文' onPress={() => i18n.changeLanguage('zh')}></Button>
        <Button title='切换为英文' onPress={() => i18n.changeLanguage('en')}></Button>
      </View>
    );
  }
}

export default withTranslation()(HomeScreen);

函数组件中使用

import React from "react";
import { View, Text, Button } from "react-native";

import { useTranslation } from 'react-i18next'


const HomeScreen = (props) => {
  // 拿到i18n
  const { i18n } = useTranslation();

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>当前语言包:{i18n.language}</Text>
      <Text>{i18n.t("hello")}{i18n.t("world")}</Text>
      <Button title='切换为中文' onPress={() => i18n.changeLanguage('zh')}></Button>
      <Button title='切换为英文' onPress={() => i18n.changeLanguage('en')}></Button>
    </View>
  );
};

export default HomeScreen;

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值