[英]React render external HTML DOM node into component when mounted
I have an external DOM node in which I display some dynamic content.我有一个外部 DOM 节点,我在其中显示一些动态内容。 That DOM node has to always be present on the page.
该 DOM 节点必须始终存在于页面上。 I also have a component
MyComponent
that is mounted/unmounted at different times.我还有一个组件
MyComponent
在不同时间安装/卸载。 When the component is mounted I want it's render method to render the existing #data
div, and when it's unmounted it should put the div back.当组件被安装时,我希望它的渲染方法来渲染现有的
#data
div,当它被卸载时,它应该把 div 放回去。
class MyComponent extends React.Component {
componentWillMount() {
// Maybe somehow move the `#data` div inside this compoennt
}
componentWillUnmount() {
// Maybe move the `#data` div back at the end of the </body> tag.
}
render() {
// Here it should just return the existing `#data` div
}
}
MyComponent not mounted: MyComponent 未安装:
<body>
<div id="app-root"></div>
<div id="data"></div> // has display: none while not used
</body>
MyComponent mounted: MyComponent 已安装:
<body>
<div id="app-root">
// React stuff
<my-component>
<div id="data"></div>
</my-component>
</div>
</body>
Is this possible (to render a plain HTML node inside a React component)?这可能吗(在 React 组件内呈现一个普通的 HTML 节点)?
Is there a better solution for my problem (have a div that's always on the page, display: none;
, but when a component is mounted, render it inside that component)?我的问题有更好的解决方案吗(有一个始终在页面上的 div,
display: none;
,但是当安装组件时,将其呈现在该组件内)?
I use this for displaying Google Ads, so I have the adDisplayContainer that has to always be present (and re-used), but I only want to show it when a specific component is shown (and it has to be inside that component).我用它来显示 Google Ads,所以我有 adDisplayContainer 必须始终存在(并重复使用),但我只想在显示特定组件时显示它(并且它必须在该组件内)。
you can use createPortal
API from ReactDOM
您可以使用来自
ReactDOM
的createPortal
API
https://reactjs.org/docs/react-dom.html#createportal https://reactjs.org/docs/react-dom.html#createportal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.