小编rug*_*ugy的帖子

ReactDom createPortal() 不起作用,但 render() 起作用,并且只有重复触发时才会起作用 - 这是为什么?

新手在这里反应一下。

TLDR:我有一个名为的辅助函数,createNotification调用该函数时会使用 render() 将<ToastNotification />组件插入到container元素中。如果我使用 createPortal() 则不会附加任何内容。如果我使用渲染,尽管有多个触发器,但该组件仅添加一次。

谁能帮我弄清楚发生了什么事吗?

谢谢

助手.js


import { ToastNotification } from "carbon-components-react";
import { render, createPortal } from "react-dom";

export const createNotification = () => {
  const container = document.getElementById("notificationContainer");
  console.log(container); //just to check function is running and has found container
  return render(<ToastNotification />, container); //works but only once, not on multiple triggers
  return createPortal(<ToastNotification />, container); //doesn't render anything in container
};
Run Code Online (Sandbox Code Playgroud)

上面的函数是根据需要从其他组件调用的:

登录.js

import { createNotification } from …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-dom carbon-design-system

3
推荐指数
1
解决办法
9898
查看次数