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

Next.js使用React-Intl国际化时遭遇FORMAT_ERROR报错求助

解决React-Intl INVALID_TAG报错及富文本链接展示问题

报错原因

直接在国际化消息字符串中嵌入HTML标签(如<a>)会触发INVALID_TAG错误,因为React-Intl默认不允许这种写法,且会自动转义HTML内容,无法直接渲染可点击的链接。

解决方案

1. 修改国际化资源文件

将消息中的HTML标签替换为占位符,保留变量结构:

{"test.modal.content": "This is {link}."}

2. 组件中使用<FormattedMessage>渲染富文本

通过values属性传递React元素作为占位符的内容,实现可点击链接:

import { FormattedMessage } from 'react-intl';

// 假设url是已定义的变量
const YourComponent = ({ url }) => {
  return (
    <FormattedMessage
      id="test.modal.content"
      values={{
        link: <a href={url} target="_blank" rel="noopener noreferrer">link</a>
      }}
    />
  );
};

3. 使用useIntl hook的场景(非组件渲染)

如果需要通过formatMessage API处理,可传入带回调的values,再通过React渲染:

import { useIntl } from 'react-intl';

const YourComponent = ({ url }) => {
  const intl = useIntl();
  const messageElements = intl.formatMessage(
    { id: 'test.modal.content' },
    {
      link: (children) => <a href={url}>{children}</a>
    }
  );

  return <span>{messageElements}</span>;
};

关键注意事项

  • 不要在国际化消息中直接写HTML标签,必须通过React元素传递富文本内容
  • 确保Locale对应的资源文件正确加载,且test.modal.content存在于当前Locale的资源中
  • 链接添加target="_blank"时,建议搭配rel="noopener noreferrer"避免安全风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:42:22