'HTMLElement | 类型的参数 null' 不可分配给类型为 'Element' 的参数。类型 'null' 不可分配给类型 'Element'.ts(2345)

IT技术 reactjs typescript react-dom
2021-05-20 21:36:38

我有 index.html

<body>
    <div id="portal"></div>
    <div id="root"></div>
</body>

并希望使用低于单独的组件portal divroot div

import React from 'react';

const portalDiv = document.getElementById('portal');

function Portal1(props) {
  return ReactDOM.createPortal(
    <div>
      {props.children}
    <div/>, 
  portalDiv); //here
}

export default Portal1;

但我收到此错误,类型为“HTMLElement |的参数” null' 不可分配给类型为 'Element' 的参数。类型 'null'在 VScode 中不能分配给类型 'Element'.ts(2345)

我正在使用typescript。请帮忙。

4个回答

其他人已经回答说你应该添加一个空检查,但 Typescript 也有一个非空断言,当你通过在语句的末尾添加运算符来确定值永远不会为空时,你可以使用!

const portalDiv = document.getElementById('#your-element')!;

所以我不知道是否有人仍然遇到这个问题,但有一个更简单直接的解决方案。只需使用“as”关键字声明模态元素即可
const modalRoot = document.getElementById("modal-root") as HTMLElement; 消除错误。我建议查看这个很棒的 react-typescript 备忘单。
https://github.com/typescript-cheatsheets/react

因为getElementById可能返回空值。所以你只需在使用之前简单地检查一下:

function Portal1({ children }) {
  return portalDiv ? ReactDOM.createPortal(<>{children}</>, portalDiv) : null;
}

getElementById可以返回null,但createPortal不接受null

如果您知道门户 div 将存在,请在代码中明确说明:

const portalDiv = document.getElementById('portal');
if (!portalDiv) {
    throw new Error("The element #portal wasn't found");
}

这将允许 TypeScript 缩小常量的类型,删除| null类型一部分。如果有人更改了某些内容,以至于当此代码不再运行时 div 不存在,它还会给您一个很好的主动警告。