JavaScript / TypeScript上是否存在类型为“节点”的节点? ts(2345)

问题描述 投票:0回答:1

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

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);
};
javascript reactjs typescript
1个回答
1
投票

问题打字稿在此发出信号是与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您确定该元素存在,并且鉴于您先前的代码,这是显而易见的。] >

© www.soinside.com 2019 - 2024. All rights reserved.