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

使用next-intl 3.11.0渲染富文本时提示缺少上下文变量p的问题

解决next-intl t.rich处理HTML文本时的"The intl string context variable 'p' was not provided"报错

问题原因

next-intl的t.rich方法是为ICU富文本语法设计的(比如{p(文本内容)}),不是用来直接解析原始HTML标签的。你当前JSON里的<p>等标签会被t.rich误识别为需要传入的ICU变量,但你的翻译字符串并没有按照ICU格式定义这些变量,因此触发报错。

解决方案

方案1:改用ICU富文本格式(推荐)

这是符合next-intl设计规范的用法,无需使用dangerouslySetInnerHTML,还能避免XSS风险。

  • 修改翻译JSON文件,将HTML标签替换为ICU富文本语法:
    {
      "...": "...",
      "text": "{p(Our company provides expert assistance and support in the following areas:)}{ol({li({p(Consultations on the legal status of migrants:)}{ul({li(Analysis of legal status and possible paths to legalization)})})})}"
    }
    
  • 调整组件代码,直接渲染t.rich返回的React元素:
    const section = searchParams.get("section")
    const id = searchParams.get("id");
    const t = useTranslations(section);
    
    return (
      <div>
        {t.rich(`${section}.${id}.text`, {
          p: (chunks) => <p>{chunks}</p>,
          strong: (chunks) => <strong>{chunks}</strong>,
          ul: (chunks) => <ul>{chunks}</ul>,
          ol: (chunks) => <ol>{chunks}</ol>,
          li: (chunks) => <li>{chunks}</li>,
        })}
      </div>
    )
    

方案2:直接渲染原始HTML(不推荐)

如果必须保留JSON中的原始HTML,无需使用t.rich,直接通过dangerouslySetInnerHTML渲染:

const section = searchParams.get("section")
const id = searchParams.get("id");
const t = useTranslations(section);

return (
  <div
    dangerouslySetInnerHTML={{
      __html: t(`${section}.${id}.text`)
    }}
  />
)

注意:此方法存在XSS安全风险,仅当翻译内容完全可信时使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:01:16