react-intl——react国际化使用方案

国际化介绍

i18n:internationalization 国家化简称,首字母+首尾字母间隔的字母个数+尾字母,类似的还有 k8s(Kubernetes) <br />
React-intl是 React 中最受欢迎的库。

使用步骤

  • 安装

    复制代码
    # use npm
    npm install react-intl -D
    # use yarn
  • 项目入口文件配置

    复制代码
    // index.tsx
    import React from "react";
    import ReactDOM from "react-dom";
    import { IntlProvider } from "react-intl";
    import App from "src/App";
    import { getCurrentLang, getCurrentMessages } from "src/locales";
    import "./styles/index.less";
    
    const root = (
      <IntlProvider locale={getCurrentLang()} messages={getCurrentMessages()}>
        <App />
      </IntlProvider>
    );
    
    ReactDOM.render(root, document.getElementById("root"));

    IntlProvider 有三个配置参数:

    • locale, <string>, 语言标记,例如 'zh-CN' 'en-US'
    • messages, <object>, 国际化所需的 key-value 对象
    • formats, <object>, 自定义 format,比如日期格式、货币等
  • 在 src/locales 中创建国际化文件,一般有 en 和 zh,如

    复制代码
    ├─src
    │  ├─en
    │  │  ├─index.ts
    │  ├─zh
    │  │  ├─index.ts
    |  |------index.ts

    添加键值对并导出

    复制代码
    // zh/index.ts
    export default {
      whatever: `你好 {placeholder}`,
    };
    
    // locales/index.ts
    import zh from './zh';
    import en from './en';
    
    import ls from 'src/utils/localStore';
    import { createIntl, createIntlCache } from 'react-intl';
    
    const _currentLang = ls.getItem('qs_lang') || 'zh-CN';
    const messages = {
      'zh-CN': zh,
      'en-US': en,
    };
    export const getCurrentLang = () => _currentLang;
    export const getCurrentMessages = () => messages[_currentLang];
    
    const cache = createIntlCache();
    const intl = createIntl(
      {
        locale: _currentLang,
        messages: getCurrentMessages(),
      },
      cache
    );
    
    export default intl;
  • 接着在组件中就可以使用FormattedMessage等组件

    复制代码
    import React from "react";
    import { FormattedMessage } from "react-intl";
    
    const App = () => {
      return (
        <FormattedMessage
          id="whatever"
          description="hello world"
          defaultMessage="Hello {placeholder}"
          values={{ placeholder: "world" }}
        />
      );
    };
    
    export default App;

    或者在函数式组件中使用 hooks

    复制代码
    import { useIntl } from "react-intl";
    
    const App = () => {
      const { formatMessage: f } = useIntl();
      return (
        <>
          {f(
            {
              id: "whatever",
              description: "hello world",
              defaultMessage: "Hello {placeholder}",
            },
            { placeholder: "world" }
          )}
        </>
      );
    };
    
    export default App;
    • <FormattedMessage>组件中可以通过values属性来传值,如以上例子传递{placeholder: 'world'},渲染到对应的你好 {placeholder}位置
    • formatMessage中传递第二个参数作为占位符的入参

如何在非组件中使用 react-intl

例如我需要在组件目录下添加constants.ts文件来管理静态变量,而且需要国际化处理,因为它不是 react 组件,所以是没法用以上的方法处理。

这时候就需要使用createIntl来处理,createIntl 允许在不使用 Provider 的情况下创建 IntlShape 对象,它返回一个可以在 React 组件外部使用的对象。

复制代码
// locales/index.ts
import { createIntl, createIntlCache } from 'react-intl';
...
const cache = createIntlCache();
const intl = createIntl(
  {
    locale: _currentLang,
    messages: getCurrentMessages(),
  },
  cache
);

export default intl;

在非组件文件中使用时

复制代码
// xxx/constants.ts
import intl from "src/locales";

const a = intl.formatMessage(
  { id: "whatever", defaultMessage: "你好 {world}" },
  { placeholder: "world" }
);

更多

react-intl还能处理像货币、时间、数字等等各种国际化问题,更多请参考官方文档

github上的demo

antd 国际化方案

参考国际化

其实就是使用 React 的 context 特性,只需要一个 Provider Component,用它来提供国际化的上下文。

复制代码
import zhCN from "antd/es/locale/zh_CN";

return (
  <ConfigProvider locale={zhCN}>
    <App />
  </ConfigProvider>
);

react-intl结合antd使用

以上步骤完成后,在切换语言为英文时,react-intl中使用的国际化文案正常显示。但此时会发现antd中组件依然显示的是中文,因为此时我们还没有对antd组件的国际化进行处理。

  1. src/locales中导出antd相关的国际化文案

  2. 在入口文件index.tsx中antd全局配置组件中引入即可

    // src/locales/index.ts
    import zh from './zh';
    import en from './en';

    import enUS from 'antd/es/locale/en_US';
    import zhCN from 'antd/es/locale/zh_CN';
    import ls from 'src/utils/localStore';
    import { createIntl, createIntlCache } from 'react-intl';

    const _currentLang = ls.getItem('qs_lang') || 'zh-CN';
    export const getCurrLang = () => _currentLang;

    const messages = {
    'zh-CN': zh,
    'en-US': en,
    };

    export const antMessages = {
    'zh-CN': zhCN,
    'en-US': enUS,
    };

    export const getAntMessages = () => antMessages[_currentLang];

    export const getCurrentMessages = () => messages[_currentLang];
    ...

    // src/index.tsx
    import React from "react";
    import ReactDOM from "react-dom";
    import { IntlProvider } from "react-intl";
    import App from "src/App";
    import { ConfigProvider } from "antd";
    import { getCurrentLang, getCurrentMessages, getAntMessages } from "src/locales";
    import "./styles/index.less";

    const root = (





    );

    ReactDOM.render(root, document.getElementById("root"));

© 著作权归作者所有,转载或内容合作请联系作者

喜欢的朋友记得点赞、收藏、关注哦!!!

相关推荐
Honmaple2 分钟前
终端 AI 编程的两条路:Pi 极简哲学 vs Oh-My-Pi 全能主义深度对决
后端
我是一颗柠檬9 分钟前
【Redis】发布订阅与消息队列Day8(2026年)
数据库·redis·后端·缓存
爱吃羊的老虎11 分钟前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python
道友可好13 分钟前
OpenSpec:轻到起飞的 AI 编程规范层
前端·人工智能·后端
IT_陈寒26 分钟前
React状态管理这个坑,我爬了整整三天才出来
前端·人工智能·后端
Love_云宝儿27 分钟前
GeoJSON简介
java·gis·地图·jts
用户83562907805141 分钟前
如何使用 Python 在 PowerPoint 演示文稿中添加漏斗图
后端
ServBay1 小时前
Qwen3.7-Max 发布,全能智能体基座
后端·aigc·ai编程
摇滚侠1 小时前
JDBC 基础到高级一套通关!进阶篇 16-27
java
KeepPush1 小时前
Python JSON 完全指南:从基础到实战,掌握数据交换核心技能
后端