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

React解析含HTML标签与尖括号内文本的报错及内容丢失问题

解决方法一:针对性处理邮箱格式的内容

用正则把邮箱格式的<xxx@xxx.xxx>替换成<xxx@xxx.xxx>,让DOMPurify把这些内容当作文本实体保留,最后渲染成正常文本:

import DOMPurify from 'dompurify';
import parse from 'html-react-parser';

const htmlString = '<p>test<br/><img src="....." />... <emailtouser@gmail.net></p>';

// 替换邮箱格式的转义尖括号,避免被DOMPurify当成HTML标签过滤
const processedHtml = htmlString.replace(
  /<([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})>/g,
  '<$1>'
);

const cleanedHTML = DOMPurify.sanitize(processedHtml);

<td>{parse(cleanedHTML)}</td>

解决方法二:通用处理所有非合法HTML标签的<...>内容

借助he库解码转义字符串,把不是合法HTML标签的<...>转成文本实体,再进行净化解析:

  1. 先安装he库:npm install he
import he from 'he';
import DOMPurify from 'dompurify';
import parse from 'html-react-parser';

const htmlString = '&lt;p&gt;test&lt;br/&gt;&lt;img src=&quot;.....&quot; /&gt;... &lt;emailtouser@gmail.net&gt;&lt;/p&gt;';

// 把转义的HTML字符串解码成原始格式
const decodedHtml = he.decode(htmlString);

// 定义你需要保留的合法HTML标签,可按需添加
const allowedTags = new Set(['p', 'br', 'img', 'div', 'span', 'strong', 'em']);

// 遍历所有<...>内容,合法标签保留,其他转成文本实体
const processedHtml = decodedHtml.replace(/<([^>]+)>/g, (match, content) => {
  const tagName = content.split(' ')[0].toLowerCase();
  return allowedTags.has(tagName) ? match : `&lt;${content}&gt;`;
});

// 重新编码后净化,再解析渲染
const cleanedHTML = DOMPurify.sanitize(he.encode(processedHtml));

<td>{parse(cleanedHTML)}</td>

为啥之前的做法不行?

  • DOMPurify会把&lt;emailtouser@gmail.net&gt;解码后的<emailtouser@gmail.net>当成无效HTML标签,直接过滤掉。
  • 不用DOMPurify的话,html-react-parser会试着把<emailtouser@gmail.net>当作HTML标签解析,但这不是合法标签,所以抛DOM异常。

这两种方法都是把要保留的<...>文本转成HTML实体,既躲开了DOMPurify的过滤,又能让html-react-parser正确渲染成文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:13:23