为什么在容器内使用 createRoot 时 React 18 会发出警告?
我正在使用React 18和NextJS,并且我做了这样一种渲染函数
export const showAlert = (props: AlertProps) => {
// it will catch <div id="alert"></div> inside _document.tsx
const container = document.getElementById('alert')
if (container) {
const root = createRoot(container)
root.render(<Alert {...props} />)
}
}
,我想使用这样的功能,
const handleClick = () => {
if (error) {
showAlert({
type: "error",
text: "Error !"
})
}
}
但反应警告这种行为:
代码> Croteroot 渲染功能?
I'm using React 18 and nextjs and I made a kind of render function like this
export const showAlert = (props: AlertProps) => {
// it will catch <div id="alert"></div> inside _document.tsx
const container = document.getElementById('alert')
if (container) {
const root = createRoot(container)
root.render(<Alert {...props} />)
}
}
And I want to use this function like this
const handleClick = () => {
if (error) {
showAlert({
type: "error",
text: "Error !"
})
}
}
But React warn of this behavior:
Anyone knows why React warn using of createRoot
for the render function ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在运行时,应仅称呼一次
During runtime, createRoot should be called only once
在运行时,您只能在特定容器上调用
createroot
。更新逻辑以创建和缓存警报root
。例子:
You should only call
createRoot
on a specific container once during runtime. Update the logic to create and cache an alertroot
.Example: