React15 - react-intl在React 15 项目中的使用

在 React 15 项目中使用 react-intl,最关键的一点是必须使用 react-intl 的 2.x 版本

这个版本是与 React 15 完全兼容的最后一个主要版本,之后的 3.x 版本要求 React 16.3+ 才能使用 useIntl 等新特性。

📦 1. 安装指定版本

使用 npm 或 yarn 安装时,需要明确指定版本号:

npm install react-intl@^2.9.0
# 或
yarn add react-intl@^2.9.0

🗂️ 2. 准备语言包文件

在项目中创建一个文件夹来存放语言包,例如 src/locales。为每种语言创建一个 JSON 文件,文件的 key 是消息的 ID,value 是对应的翻译文本。

src/locales/en.json

{
  "app.title": "Welcome to My App",
  "app.greeting": "Hello, {name}!"
}

src/locales/zh.json

{
  "app.title": "欢迎使用我的应用",
  "app.greeting": "你好,{name}!"
}

🔧 3. 在项目入口配置 IntlProvider

在你的根组件(通常是 App.jsindex.js)中,引入 IntlProvider 并包裹整个应用。你需要传入当前的语言环境 (locale) 和对应的消息对象 (messages)。

import React, { Component } from "react";
import { IntlProvider } from "react-intl";
// 引入语言包
import enMessages from "./locales/en.json";
import zhMessages from "./locales/zh.json";

// 定义一个组件来管理语言状态
class App extends Component {
  constructor(props) {
    super(props);
    // 初始化语言,可以从浏览器或本地存储中获取
    this.state = {
      locale: "en",
      messages: enMessages,
    };
  }

  // 切换语言的方法
  handleLocaleChange = (newLocale) => {
    let newMessages;
    switch (newLocale) {
      case "zh":
        newMessages = zhMessages;
        break;
      default:
        newMessages = enMessages;
        break;
    }
    this.setState({
      locale: newLocale,
      messages: newMessages,
    });
  };

  render() {
    return (
      // IntlProvider 提供国际化上下文给所有子组件
      <IntlProvider locale={this.state.locale} messages={this.state.messages}>
        <div className="App">
          {/* 将切换语言的方法传递给子组件 */}
          <LanguageSwitcher onSwitch={this.handleLocaleChange} />
          {/* 你的其他组件 */}
          <MyComponent />
        </div>
      </IntlProvider>
    );
  }
}

export default App;

🖥️ 4. 在组件中使用

在需要使用翻译的组件中,主要有两种方式:

方式一:使用 FormattedMessage 组件(最常用)

适用于直接在 JSX 中渲染文本。defaultMessage 属性会作为找不到翻译时的后备内容,有助于开发和调试。

import React from "react";
import { FormattedMessage } from "react-intl";

const MyComponent = () => {
  return (
    <div>
      <h1>
        {/* 渲染一个简单的标题,对应 messages 中 id 为 'app.title' 的值 */}
        <FormattedMessage id="app.title" defaultMessage="Welcome to My App" />
      </h1>
      <p>
        {/* 渲染带参数的文本,通过 values 属性传入动态值 */}
        <FormattedMessage
          id="app.greeting"
          defaultMessage="Hello, {name}!"
          values={{ name: "React 15 User" }}
        />
      </p>
    </div>
  );
};

export default MyComponent;

方式二:使用 injectIntl 高阶组件(用于非组件场景)

如果你需要在组件的 props 或方法中(例如在 placeholderaria-label 属性中)使用翻译后的文本,可以使用 injectIntl HOC,它会将 intl 对象注入到组件的 props 中。

import React, { Component } from "react";
import { injectIntl, defineMessages } from "react-intl";

// 定义需要翻译的消息
const messages = defineMessages({
  searchPlaceholder: {
    id: "app.search.placeholder",
    defaultMessage: "Search...",
  },
});

class SearchBox extends Component {
  render() {
    // 从 props 中获取 intl 对象
    const { intl } = this.props;
    return (
      <input
        type="text"
        // 使用 formatMessage 方法获取翻译后的字符串
        placeholder={intl.formatMessage(messages.searchPlaceholder)}
      />
    );
  }
}

// 使用 injectIntl 包裹组件,将 intl 对象作为 prop 传入
export default injectIntl(SearchBox);

⚠️ 常见问题与注意事项

  • 关于 Intl API 的 polyfill:React 15 项目经常运行在较旧的浏览器(如 IE 11)上。react-intl 依赖于浏览器原生的 Intl API。如果你的目标环境不支持,需要手动引入 polyfill,以确保日期、数字等格式化功能正常。

    <!-- 在 public/index.html 中引入,或在入口文件最顶部引入 -->
    <script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=Intl.~locale.en"></script>
    

    也可以考虑使用 intl 这个 npm 包,并在入口文件最顶部 require('intl')

  • 版本选择的重要性:绝对不要尝试在 React 15 项目中使用 react-intl 的 3.x 或更高版本,这会导致不可预知的错误。如果你的项目未来计划升级到 React 16.8+,可以考虑届时再一并升级 react-intl

  • 与 Ant Design 等组件库的配合:如果项目中使用了 Ant Design (v3),需要分别处理。react-intl 负责你的业务文案,而 Ant Design 的国际化需要单独配置 LocaleProvider 组件。这两者需要切换语言时同步更新。

posted @ 2026-03-22 22:31  箫笛  阅读(3)  评论(0)    收藏  举报