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