zoukankan      html  css  js  c++  java
  • react添加/嵌入 iframe

      

    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={{  1120, border: 0, height: iframeHeight }}
          sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
          scrolling="auto"
        ></iframe>
      )
    }
    

      

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

  • 相关阅读:
    view间传值的方法总结
    初学者关于内存的思考(不断加深不断更新中)
    UITableView刷新数据reLoadData
    rsync安装指南
    Makefile完全解析PART5.使用变量
    Makefile完全解析PART10.使用make更新函数库文件
    windows linux 文件同步 cwrsync工具
    Makefile完全解析PART4.书写命令
    Makefile完全解析PART7.使用函数
    RSYNC安装使用详解
  • 原文地址:https://www.cnblogs.com/zhangym118/p/13255043.html
Copyright © 2011-2022 走看看