使用html-react-parse解析含(e.g.,)文本时触发DOMException错误
问题分析
你遇到的错误是因为html-react-parser和react-html-parse的底层解析器会误将文本中(e.g.,这类括号开头的内容识别为无效HTML标签,进而抛出创建元素失败的异常。
解决方案
方案1:预处理文本转义圆括号
通过将圆括号转换为HTML实体,避免解析器误判为HTML标签起始符,同时保留合法的HTML标签解析:
import React from "react"; import parse from 'html-react-parser'; export function App(props) { function getSearchHighlight(highlight) { try { // 转义圆括号为HTML实体,阻止解析器误判 const processedText = highlight .replace(/\(/g, '(') .replace(/\)/g, ')'); return parse(processedText); } catch (e) { return "Issues with search highlight " + e; } } return ( <div className="App"> <h1>Hello React Parse.</h1> <p> {getSearchHighlight( "Comparison to this and that <em>information</em> (e.g., those surveys)." )} </p> </div> ); }
方案2:用解析器替换回调拦截无效标签
利用html-react-parser的replace配置,捕获解析器识别的无效标签,将其转换为对应文本内容:
import React from "react"; import parse from 'html-react-parser'; export function App(props) { function getSearchHighlight(highlight) { try { return parse(highlight, { replace: (domNode) => { // 仅允许解析<em>标签,其他识别出的标签转为带括号的文本 if (domNode.type === 'tag' && domNode.name !== 'em') { return `(${domNode.name})`; } } }); } catch (e) { return "Issues with search highlight " + e; } } return ( <div className="App"> <h1>Hello React Parse.</h1> <p> {getSearchHighlight( "Comparison to this and that <em>information</em> (e.g., those surveys)." )} </p> </div> ); }
方案说明
- 方案1从根源避免误判,适合包含多种括号类文本的通用场景;
- 方案2精准拦截无效标签,适合明确知道需要保留哪些HTML标签的场景;
- 两种方案均无需使用
dangerouslySetInnerHTML,同时能正常解析<em>这类合法高亮标签。
内容的提问来源于stack exchange,提问作者Bradley Pennington
相关产品推荐
相关产品推荐

