const [containerEl] = useState(document.createElement('div'));
EDIT
(编辑)
Button onClick event, invoke first call of functional component PopupWindowWithHooks and it works as expected (create new <div>
, in useEffect append <div>
to popup window).
(Button onClick事件,调用功能组件PopupWindowWithHooks的 首次调用,它按预期方式工作(在useEffect中创建新的<div>
,将<div>
追加到弹出窗口)。)
The event refresh, invoke second call of functional component PopupWindowWithHooks and line const containerEl = document.createElement('div')
create new <div>
again.
(事件刷新后,调用功能组件PopupWindowWithHooks的 第二次调用,并在const containerEl = document.createElement('div')
再次创建新的<div>
。)
But that (second) new <div>
will never be appended to popup window, because line externalWindow.document.body.appendChild(containerEl)
is in useEffect hook that would run only on mount and clean up on unmount (the second argument is an empty array []).(但是,(第二个)新的<div>
将永远不会追加到弹出窗口,因为在代码中使用了externalWindow.document.body.appendChild(containerEl)
行,该钩子仅在mount上运行,而在unmount上清除(第二个参数是空数组[])。)
Finally return ReactDOM.createPortal(props.children, containerEl)
create portal with second argument containerEl - new unappended <div>
(最后return ReactDOM.createPortal(props.children, containerEl)
创建带有第二个参数containerEl的门户-新的未附加<div>
)
With containerEl as a stateful value (useState hook), problem is solved:
(使用containerEl作为有状态值(useState挂钩),可以解决以下问题:)
const [containerEl] = useState(document.createElement('div'));
EDIT2
(编辑2)
Code Sandbox: https://codesandbox.io/s/l5j2zp89k9
(代码沙箱: https : //codesandbox.io/s/l5j2zp89k9)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…