根据Reaction文档,‘React Portals’允许我们将子组件呈现到父组件的DOM层次 struct 之外的DOM node 中.基本上,portals let us render children个我们想要的地方.
因此,最大的解释是创建一个门户:
ReactDOM.createPortal(child, container)
在本例中,子对象是react element、fragment或string,而容器是门户应该呈现到的DOM
位置或 node .
使用Reaction门户,我们可以 Select 在DOM层次 struct 中放置DOM node 的位置,门户的内容也被视为父virtual DOM的子 node .
MyComponent.js个
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;
我们创建了一个带有useState()
钩子的引用,因此,一旦更新了状态,组件将重新呈现.
我们还访问了iframe文档正文,然后创建了一个门户来呈现子passed to iframe in this body:
import './App.css';
import CustomIframe from './CustomIframe';
import MyComponent from './MyComponent';
function App() {
return (
<CustomIframe title='A custom made iframe'>
<MyComponent />
</CustomIframe>
);
}
export default App;
你可以作为CustomIframe
岁的子元素传递任何Reaction应用程序或组件,它应该运行得很好.
Reaction应用程序或组件将变为encapsulated,这意味着您可以独立开发和维护它.
您还可以使用一个名为Reaction Frame Component的库来实现与上面相同的封装.要安装它,请运行以下命令:
npm install --save react-frame-component
按如下方式封装组件:
import Frame from 'react-frame-component';
function App() {
return (
<div className='App'>
<p>Iframes in React</p>
<Frame >
<MyComponent />
</Frame>
</div>
);
}
export default App;