react如何显示html文本
渲染HTML文本的方法
在React中渲染HTML文本需要使用dangerouslySetInnerHTML属性,该属性允许直接将HTML字符串插入到DOM中。需要注意的是,使用此方法可能存在XSS(跨站脚本攻击)风险,因此必须确保HTML内容来源可信。
function DisplayHTML({ htmlContent }) {
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
}
处理XSS风险
为了降低安全风险,可以使用DOMPurify等库对HTML内容进行清理:

import DOMPurify from 'dompurify';
function SafeHTML({ htmlContent }) {
const cleanHTML = DOMPurify.sanitize(htmlContent);
return <div dangerouslySetInnerHTML={{ __html: cleanHTML }} />;
}
替代方案
如果不希望使用dangerouslySetInnerHTML,可以考虑以下替代方法:
使用第三方库如react-html-parser:

import ReactHtmlParser from 'react-html-parser';
function ParseHTML({ htmlContent }) {
return <div>{ReactHtmlParser(htmlContent)}</div>;
}
样式处理
当渲染HTML内容时,可能需要处理内联样式或类名。确保样式作用域正确,避免影响其他组件:
function StyledHTML({ htmlContent }) {
return (
<div
className="html-content-wrapper"
dangerouslySetInnerHTML={{ __html: htmlContent }}
/>
);
}
在CSS中:
.html-content-wrapper p {
margin: 1em 0;
}
.html-content-wrapper img {
max-width: 100%;
}






