如何封装 Trans 组件支持 JSX 嵌套与变量替换

解读

国内业务普遍要求“国际化文案 + 富文本”同时落地,例如“亲爱的 {user},您还有 <strong>3</strong> 张优惠券,<a>立即使用</a>”。
面试官想确认三件事:

  1. 你是否理解 React 的“元素即对象”本质,敢不敢直接操作 children;
  2. 能否在“不污染翻译语料”的前提下做变量替换与标签占位;
  3. 是否具备工程化思维:TypeScript 类型安全、性能、可维护性、与主流 i18n 方案(react-i18next、lingui、next-intl)的对接方式。

知识点

  • React.createElement / React.isValidElement / React.cloneElement
  • JSX 的语法糖本质:编译后就是 _jsx(tag, props, key) 调用
  • 递归遍历 children 的“双端对比”技巧:一边扫描翻译字符串得到的占位符数组,一边扫描 React 节点树,保证 O(n) 复杂度
  • 占位符语法设计:ICU 风格 {var} 与标签占位 <0>…</0> 混用,避免正则回溯
  • 类型体操:TypeScript 模板字面量推断 + 泛型约束,实现“翻译 key 对应变量名”自动提示
  • 与 react-i18next 的 Trans 组件差异:官方实现基于 ast 与 i18next-parser,封装时需权衡“零依赖”还是“直接复用”
  • 性能细节:memo + 缓存编译结果,防止每次 render 重复解析;使用 useRef 保存上一次 i18n 语言,语言变化时才重新编译
  • 安全:禁止在翻译字符串中直接出现 HTML,防止 XSS;所有富文本必须通过 JSX 注入

答案

// i18n.ts
const dict = {
  zh: {
    welcome: '欢迎 <bold>{user}</bold>,您有 <link>{count} 张券</link>,<highlight>立即使用</highlight>。',
  },
  en: {
    welcome: 'Welcome <bold>{user}</bold>, you have <link>{count} coupons</link>, <highlight>use now</highlight>.',
  },
} as const;

type Locale = keyof typeof dict;
type I18nKey = keyof (typeof dict)[Locale];

let currentLocale: Locale = 'zh';
export const setLocale = (l: Locale) => (currentLocale = l);
export const t = (key: I18nKey, vars?: Record<string, React.ReactNode>) => {
  let str = dict[currentLocale][key];
  if (!str) return key;
  if (vars) {
    Object.entries(vars).forEach(([k, v]) => {
      str = str.replace(new RegExp(`\\{${k}\\}`, 'g'), String(v));
    });
  }
  return str;
};

// Trans.tsx
import React, { memo, useMemo, isValidElement, cloneElement, ReactNode } from 'react';

type TransProps<K extends I18nKey> = {
  i18nKey: K;
  values?: Record<string, React.ReactNode>;
  components?: Record<string, React.ReactNode>;
  fallback?: ReactNode;
};

// 轻量级编译器:把翻译字符串拆成 [{type:'text'|'tag'|'var', value:string, children?:...}]
function compile(
  tpl: string,
  values: Record<string, React.ReactNode> = {},
  components: Record<string, React.ReactNode> = {},
) {
  const stack: Array<{ type: 'tag'; name: string; children: ReactNode[] }> = [];
  const root: ReactNode[] = [];
  let buffer = '';
  let i = 0;

  const pushText = () => {
    if (buffer) {
      const target = stack.length ? stack[stack.length - 1].children : root;
      target.push(buffer);
      buffer = '';
    }
  };

  while (i < tpl.length) {
    // 1. 匹配变量 {var}
    if (tpl[i] === '{' && tpl[i + 1] !== '{') {
      const close = tpl.indexOf('}', i);
      if (close > i) {
        pushText();
        const key = tpl.slice(i + 1, close);
        const target = stack.length ? stack[stack.length - 1].children : root;
        target.push(values[key] || `{${key}}`);
        i = close + 1;
        continue;
      }
    }
    // 2. 匹配标签 <0> <1> …
    if (tpl.slice(i, i + 2) === '</') {
      const close = tpl.indexOf('>', i);
      if (close > i) {
        pushText();
        stack.pop();
        i = close + 1;
        continue;
      }
    }
    if (tpl[i] === '<' && /\d/.test(tpl[i + 1])) {
      const close = tpl.indexOf('>', i);
      if (close > i) {
        pushText();
        const index = tpl.slice(i + 1, close);
        const target = stack.length ? stack[stack.length - 1].children : root;
        const vnode = components[index];
        if (vnode) {
          const slot: ReactNode[] = [];
          stack.push({ type: 'tag', name: index, children: slot });
          target.push(
            cloneElement(vnode as any, {}, slot),
          );
        }
        i = close + 1;
        continue;
      }
    }
    buffer += tpl[i++];
  }
  pushText();
  return root;
}

export const Trans = memo(<K extends I18nKey>({ i18nKey, values, components, fallback }: TransProps<K>) => {
  const raw = t(i18nKey);
  const nodes = useMemo(() => {
    if (!raw) return fallback ?? i18nKey;
    return compile(raw, values, components);
  }, [raw, values, components, fallback]);
  return <>{nodes}</>;
}) as <K extends I18nKey>(p: TransProps<K>) => JSX.Element;

// 使用示例
function CouponBanner({ user, count }: { user: string; count: number }) {
  return (
    <Trans
      i18nKey="welcome"
      values={{ user, count }}
      components={{
        bold: <strong />,
        link: <a href="/coupons" className="link" />,
        highlight: <span className="highlight" />,
      }}
    />
  );
}

要点回顾

  1. 翻译语料只存“纯文本 + 占位符”,不含业务标签,方便交给翻译团队。
  2. 组件映射通过“数字索引”实现,避免在语料里写标签名,降低耦合。
  3. 编译过程一次性把字符串拆成结构化数据,后续仅做 cloneElement,不操作 dangerouslySetInnerHTML,天然防 XSS。
  4. 整个 Trans 用 memo 包一层,key、values、components 不变就不会重编译。

拓展思考

  1. 如果项目已用 react-i18next,可直接复用它的 Trans 组件,但需理解其 ast 解析器(i18next-icu 或 i18next-parser)如何与 webpack/vite 插件联动,实现“提取语料 + 自动给占位符编号”。
  2. 当文案量巨大时,可把 compile 结果做 LRU 缓存,甚至移到 WebWorker 里做流式解析,避免主线程卡顿。
  3. 需要支持复数、性别、区间时,可引入 ICU MessageFormat,在 compile 阶段调用 intl-messageformat,把“{count, plural, one{#张} other{#张}}”一并解析。
  4. 服务端渲染场景下,要把当前语言注入到 window.INITIAL_I18N,保证同构输出一致;同时利用 React 18 的 streaming SSR,把翻译分片流式打到前端。
  5. 测试策略:
    • 单元测试用 @testing-library/react,断言“传入同样 key 与变量,输出节点树一致”;
    • 集成测试用 cypress + 伪本地化(pseudolocalization),验证长文本不会撑爆布局;
    • 自动化扫描用 i18next-parser 提取,对比 Figma 插件导出的语料,防止“key 遗漏、占位符不一致”。