簡體   English   中英

ref 的作用是什么以及為什么它在 iframe 中是必要的?

[英]What ref does and why it's necessary in iframes?

import React from 'react'

function MyComponent() {
    return (
        <div>
            <p style={{color: 'red'}}>Testing to see if my component renders!</p>
        </div>
    )
}

export default MyComponent;

現在,讓我們創建一個文件 CustomIframe.js

import React, { useState } from 'react'
import { createPortal } from 'react-dom'

const CustomIframe = ({
  children,
  ...props
}) => {
  const [contentRef, setContentRef] = useState(null)

  const mountNode =
    contentRef?.contentWindow?.document?.body

  return (
    <iframe {...props} ref={setContentRef}>
      {mountNode && createPortal(children, mountNode)}
    </iframe>
  )
}

export default CustomIframe;
  1. ref 的回報是什么? 為什么需要它? 為什么在 ref={} 中使用 setContentRef 而不是 contentRef?

  2. 除此之外,為什么 {...props} 出現在 iframe 標簽中,而它們在任何地方都沒有被消耗?

我試着在網上找 ref,只知道 useRef hook,不知道 ref

  1. setContentRef會將 iframe 元素引用分配給contentRef ,因此您可以訪問 iframe 中可用的本機方法和屬性,例如contentWindow

  2. {...props}會將 props 中的所有值作為 iframe 元素的屬性展開

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM