javascript - JavaScript/TypeScript 上是否存在类型 'Node'? TS(2345)

标签 javascript reactjs typescript

我正在尝试在 React 上创建一个 Modal,并使用 TypeScript。我收到“Node 类型参数”错误,但无法弄清楚这是什么(随后也无法解决我的问题)。

const Modal = ({ children }: { children: any }) => {
  const elRef = useRef<HTMLDivElement | null>(null); //tried adding'| Node'
  if (!elRef.current) {
    const div = document.createElement("div");
    div.className = "modalDiv";
    elRef.current = div;
  }

  useEffect(() => {
    const modalRoot = document.getElementById("modal");
//Argument of type 'HTMLDivElement | null' is not assignable to parameter of type 'Node'.
//Type 'null' is not assignable to type 'Node'.ts(2345)
    modalRoot!.appendChild(elRef.current);

    return () => modalRoot!.removeChild(elRef.current);
  }, []);

  return createPortal(<div>{children}</div>, elRef.current);
};

最佳答案

typescript 发出的问题与Node无关。 Node 是通用 DOM 元素,并且 HTMLDivElement 匹配正确。问题在于它可能采用的 null 值,而 null 显然不是 Node,因此您不能在 appendChild 中使用 null

您应该添加一个类似 if (elRef.current != null) { ... } 的检查,以确保 HTMLDivElement 已正确创建。

useEffect(() => {
    const modalRoot = document.getElementById("modal");
    if (elRef.current) modalRoot!.appendChild(elRef.current);

    return () => {
      if (elRef.current) modalRoot!.removeChild(elRef.current);
    }
  }, []);

一种更简单的方法(在本例中,是一种更合乎逻辑的方法)就是使用 elRef.current! 告诉 TS 您确定该元素是存在,鉴于您之前的代码,这一点很清楚。

关于javascript - JavaScript/TypeScript 上是否存在类型 'Node'? TS(2345),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61422906/

相关文章:

reactjs - 具有通用初始类型的高阶组件

javascript - 在呈现 View 之前从父级设置子组件属性

javascript - 未能 "dynamically"导入 date-fns/locale 库 - TypeScript 给出尝试导入错误

javascript - 单击按钮时组件未呈现 - ReactJS

reactjs - React 应用程序 npm 错误代码 ELIFECYCLE

javascript - 从命令行预先简化 topojson

javascript - 防止更改 Jquery 中的文本框值

javascript - 在 react router v6 中使用导航功能时如何传递数据

javascript - 使用 Socket.io 广播消息时出现问题

php - 仅在提交时使用 javascript 保存表单状态