为什么在容器内使用 createRoot 时 React 18 会发出警告?

发布于 2025-01-20 07:30:09 字数 651 浏览 3 评论 0原文

我正在使用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:

enter image description here

Anyone knows why React warn using of createRoot for the render function ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只有一腔孤勇 2025-01-27 07:30:09

在运行时,应仅称呼一次

During runtime, createRoot should be called only once

ら栖息 2025-01-27 07:30:09

在运行时,您只能在特定容器上调用createroot。更新逻辑以创建和缓存警报root

例子:

let root: Root | null = null;

const showAlert = (props: AlertProps) => {
  const container = document.getElementById("alert");
  if (container) {
    root = root ?? createRoot(container);
    root.render(<Alert {...props} />);
  }
};

You should only call createRoot on a specific container once during runtime. Update the logic to create and cache an alert root.

Example:

let root: Root | null = null;

const showAlert = (props: AlertProps) => {
  const container = document.getElementById("alert");
  if (container) {
    root = root ?? createRoot(container);
    root.render(<Alert {...props} />);
  }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文