react+chakraUI 渲染富文本内容
1、dangerouslySetInnerHTML
react渲染富文本内容可以使用dangerouslySetInnerHTML属性。这个属性允许你设置HTML字符串,但是要非常小心,因为它可能会导致跨站脚本攻击(XSS)。确保你的富文本内容是安全的或已经被清洗过。使用这个属性不能隔离富文本中的样式,容易造成样式污染。示例:
const RichContent = ()=>{
const html=`<div>富文本内容</div>`
return(
<Box dangerouslySetInnerHTML={{ __html: html }} />
)
}
export default RichContent;
2、iframe
通过使用iframe标签来实现渲染富文本内容,这样可以隔离富文本中的样式,避免样式污染。实现步骤:获取到iframe标签,首先调用open方法打开一个新文档,在调用write方法写入富文本内容,在close文档,示例:
import { useEffect, useState, useRef } from 'react';
export function WebView({ content }: { content: string }) {
const Iframe=useRef<any>(null)
useEffect(()=>{
if(Iframe.current&&content){
const iframeDocument = Iframe.current?.contentWindow.document
const styleElement = document.createElement('style');
styleElement.textContent = 'body { overflow: hidden !important}';
iframeDocument.open();
iframeDocument.write(content);
iframeDocument.head.appendChild(styleElement);
iframeDocument.close();
//可以获取到iframe的高度
const bodyHeight = iframeDocument.body.offsetHeight;
console.log('bodyHeight======',bodyHeight)
}
},[content])
return (
<iframe width={'100%'} height={'100%'} ref={Iframe}></iframe>
)
}