[英]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;
ref 的回報是什么? 為什么需要它? 為什么在 ref={} 中使用 setContentRef 而不是 contentRef?
除此之外,為什么 {...props} 出現在 iframe 標簽中,而它們在任何地方都沒有被消耗?
我試着在網上找 ref,只知道 useRef hook,不知道 ref
setContentRef
會將 iframe 元素引用分配給contentRef
,因此您可以訪問 iframe 中可用的本機方法和屬性,例如contentWindow
{...props}
會將 props 中的所有值作為 iframe 元素的屬性展開
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.