查看: 83|回复: 0

react添加/嵌入 iframe

[复制链接]

6

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2012-2-26
发表于 2020-7-6 15:29:00 | 显示全部楼层 |阅读模式

  

react 嵌入 iframe 主要是为了隔离富文本,避免跟宿主环境的样式、变量等造成污染。

 

情况1:后端返回一个完整的网页,前端直接 `<iframe src="$url"></iframe>` 就可以了。

情况2:后端返回内容不可控 (比如以下例子)。

 

用法:

index.tsx:

export default function Iframe () {
  const contentIFrameRef = useRef<HTMLIFrameElement>(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="<h1>标题</h1>")
        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 (
    <iframe
      ref={contentIFrameRef}
      title="iframe"
      style={{ width: 1120, border: 0, height: iframeHeight }}
      sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
      scrolling="auto"
    ></iframe>
  )
}

  

如果后端把 iframe 的内容放在服务端,返给前端一个 url,可以直接 <iframe src={Url}></iframe>

 



来源:https://www.cnblogs.com/zhangym118/p/13255043.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部