【发布时间】:2019-09-23 09:53:30
【问题描述】:
我有一个外部 DOM 节点,我在其中显示一些动态内容。该 DOM 节点必须始终存在于页面上。我还有一个组件MyComponent,它在不同时间安装/卸载。当组件被挂载时,我希望它的 render 方法呈现现有的#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 未安装:
<body>
<div id="app-root"></div>
<div id="data"></div> // has display: none while not used
</body>
MyComponent 已安装:
<body>
<div id="app-root">
// React stuff
<my-component>
<div id="data"></div>
</my-component>
</div>
</body>
这可能吗(在 React 组件中呈现纯 HTML 节点)?
有没有更好的解决方案来解决我的问题(有一个始终在页面上的 div,display: none;,但是当安装组件时,将其呈现在该组件内)?
我用它来显示 Google Ads,所以我有 adDisplayContainer 必须始终存在(并重复使用),但我只想在显示特定组件时显示它(并且它必须在其中组件)。
【问题讨论】:
-
我认为您需要创建一个 HOC,在其中您将组件作为子组件传递,它将为您提供带有 adDisplayContainer 的子组件。
-
到目前为止,我通过使用一个始终在页面上可见且包含广告容器的组件解决了我的问题。
MyComponent在里面,可以在任何时候安装/卸载。 HTML 结构与我的问题不同,但我无法在不中断广告播放的情况下移动广告容器。
标签: javascript html reactjs dom