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={{ 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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM