You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用lingui.js翻译React中的静态提示语与占位符

解决lingui.js中动态提示语和组件占位符的翻译配置问题

核心原因

你用i18n._()直接包裹字符串时,lingui的提取工具默认只会识别宏标记的内容(如<Trans>、t、defineMessage宏),普通字符串不会被扫描到PO文件中。下面针对两种场景给出具体配置方法:


场景1:按钮触发的动态提示语(如Toast.error)

改用@lingui/macro提供的t宏标记待翻译字符串,再传入i18n._()处理:

// 1. 引入t宏
import { t } from "@lingui/macro";
// 函数组件用useLingui hook获取i18n,类组件需通过withI18n高阶组件注入
import { useLingui } from "@lingui/react";

function MyComponent() {
  const { i18n } = useLingui();

  const handleClick = () => {
    // 2. 用t宏包裹原始字符串,再传给i18n._()
    Toast.error(i18n._(t`Please select security code preference`));
  };

  return <button onClick={handleClick}>Submit</button>;
}

如果需要复用该提示语,推荐用defineMessage宏定义,可读性更强:

import { defineMessage } from "@lingui/macro";

// 提前定义消息(支持自定义id,方便管理)
const securityCodeError = defineMessage({
  id: "toast.security.code.error",
  message: "Please select security code preference",
});

// 使用时
Toast.error(i18n._(securityCodeError));

场景2:输入组件的占位符(如Select的placeholder)

同样用t宏标记字符串,通过i18n._()生成翻译后的文本作为props传入:

import { useLingui } from "@lingui/react";
import { t } from "@lingui/macro";
import Select from "your-select-component";

function MyComponent() {
  const { i18n } = useLingui();

  return (
    <Select
      // 直接将翻译后的字符串赋值给placeholder属性
      placeholder={i18n._(t`Select security code preference`)}
    />
  );
}

验证步骤

  1. 运行lingui extract命令,检查PO文件中是否出现了这些标记的字符串
  2. 完成翻译后执行lingui compile
  3. 重启项目即可看到翻译效果

内容的提问来源于stack exchange,提问作者Yashpal S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 09:55:10