react 嵌入 iframe 主要是为了隔离富文本,避免跟宿主环境的样式、变量等造成污染。
情况1:后端返回一个完整的网页,前端直接 `` 就可以了。
情况2:后端返回内容不可控 (比如以下例子)。
用法:
index.tsx:
export default function Iframe () {
const contentIFrameRef = useRef(null)
const [iframeHeight, setIframeHeight] = useState(0)
useEffect(() => {
$api.xxxxx(xxx)
.then((res) => {
const iframe: HTMLIFrameElement | null = contentIFrameRef.current
if (iframe && iframe.contentWindow) {
const iframeDocument = iframe.contentWindow.document
// 写入内容(这里举例的 iframe 内容是请求接口后返回 html,也就是 res,比如 res="
标题
")iframeDocument.write(res)
// 如果需要 css,写入 css,此处的 css 是写在根目录里(与 index.html 同级)
if (!(iframeDocument.getElementsByTagName('link')[0])) {
const link = iframeDocument.createElement('link')
link.href = process.env.PUBLIC_URL + '/template.css'
link.rel = 'stylesheet'
link.type = 'text/css'
iframeDocument.head.appendChild(link)
}
// 这里动态计算 iframe 的 height,这里举例 300px
setIframeHeight(300)
}
})
}, [])
return (
ref={contentIFrameRef}
title="iframe"
style={{ width: 1120, border: 0, height: iframeHeight }}
sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
scrolling="auto"
>
)
}
如果后端把 iframe 的内容放在服务端,返给前端一个 url,可以直接