React解析含HTML标签与尖括号内文本的报错及内容丢失问题
解决方法一:针对性处理邮箱格式的内容
用正则把邮箱格式的<xxx@xxx.xxx>替换成&lt;xxx@xxx.xxx&gt;,让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, '&lt;$1&gt;' ); const cleanedHTML = DOMPurify.sanitize(processedHtml); <td>{parse(cleanedHTML)}</td>
解决方法二:通用处理所有非合法HTML标签的<...>内容
借助he库解码转义字符串,把不是合法HTML标签的<...>转成文本实体,再进行净化解析:
- 先安装
he库:npm install he
import he from 'he'; import DOMPurify from 'dompurify'; import parse from 'html-react-parser'; const htmlString = '<p>test<br/><img src="....." />... <emailtouser@gmail.net></p>'; // 把转义的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 : `<${content}>`; }); // 重新编码后净化,再解析渲染 const cleanedHTML = DOMPurify.sanitize(he.encode(processedHtml)); <td>{parse(cleanedHTML)}</td>
为啥之前的做法不行?
- DOMPurify会把
<emailtouser@gmail.net>解码后的<emailtouser@gmail.net>当成无效HTML标签,直接过滤掉。 - 不用DOMPurify的话,html-react-parser会试着把
<emailtouser@gmail.net>当作HTML标签解析,但这不是合法标签,所以抛DOM异常。
这两种方法都是把要保留的<...>文本转成HTML实体,既躲开了DOMPurify的过滤,又能让html-react-parser正确渲染成文本。
内容的提问来源于stack exchange,提问作者may saghira
相关产品推荐
相关产品推荐

