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

2024-04-16

我有index.html

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

并想单独使用下面的组件portal div than root 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”不可分配给类型“Element”.ts(2345)在 VScode 中。

我正在使用打字稿。


其他人回答说你应该添加一个空检查,但是 Typescript 也有一个非空断言,你可以在以下情况下使用:sure通过添加该值永远不会为空!运算符添加到语句末尾:

const portalDiv = document.getElementById('your-element')!;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

'HTMLElement | 类型的参数null' 不可分配给'Element' 类型的参数。类型“null”不可分配给类型“Element”.ts(2345) 的相关文章

随机推荐