我正在尝试在 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/