React富文本无法按HTML格式显示?React Quill渲染异常求助
问题解决:React中渲染转义HTML丢失格式
问题背景
使用React Quill富文本编辑器保存HTML格式的教育经历数据,API返回的education字段为双重转义后的HTML字符串:
"education": "<ul><li>Bachelor of Science (BSc) in Computer Science & Engineering, </li><li>Master of Science (MSc) in Computer Science & Engineering</li></ul><p><br></p>"
尝试用dangerouslySetInnerHTML配合DOMPurify渲染时,仅显示纯文本,列表等格式完全丢失。
原因分析
API返回的字符串是双重转义的HTML:原始的<被转成了<,&被转成了&。直接渲染时,浏览器会将这些转义字符识别为纯文本,而非可解析的HTML标签。
解决方案
需要先将转义的HTML字符还原为原始HTML,再进行安全净化和渲染。
方法1:使用he库解码(推荐)
he是专门处理HTML实体的库,能可靠解码转义字符。
- 安装依赖:
npm install he # 或 yarn add he
- 修改代码:
import DOMPurify from "dompurify"; import he from "he"; const sanitizeHTML = (html) => { // 先解码转义的HTML实体 const decodedHTML = he.decode(html); // 净化后返回可渲染的HTML对象 return { __html: DOMPurify.sanitize(decodedHTML), }; }; // 渲染组件 <div className="text-lg" dangerouslySetInnerHTML={sanitizeHTML(jobDescription.education)} />
方法2:用原生DOM API解码(无需额外依赖)
通过临时DOM元素的textContent属性自动解码转义字符:
import DOMPurify from "dompurify"; const sanitizeHTML = (html) => { const tempElement = document.createElement("div"); tempElement.innerHTML = html; // 获取解码后的原始HTML const decodedHTML = tempElement.textContent; return { __html: DOMPurify.sanitize(decodedHTML), }; }; // 渲染组件 <div className="text-lg" dangerouslySetInnerHTML={sanitizeHTML(jobDescription.education)} />
效果验证
处理后,浏览器会正确解析HTML标签,显示出预期的列表格式:
- Bachelor of Science (BSc) in Computer Science & Engineering,
- Master of Science (MSc) in Computer Science & Engineering
内容的提问来源于stack exchange,提问作者Tia Mat
相关产品推荐
相关产品推荐

