我有index.html
并希望单独使用下面的组件portal div比root div
import React from 'react';
const portalDiv = document.getElementById('portal');
function Portal1(props) {
return ReactDOM.createPortal(
{props.children}
,
portalDiv); //here
}
export default Portal1;但我得到了这个错误,“HTMLElement | null”类型的参数不能分配给“Element”类型的参数。类型“null”不可分配给VScode中的类型“Element”.ts(2345)。
我正在使用打字脚本。请帮忙。
发布于 2020-08-21 18:04:13
因为getElementById可能返回null。因此,您只需在使用like之前进行检查即可:
function Portal1({ children }) {
return portalDiv ? ReactDOM.createPortal(<>{children}, portalDiv) : null;
}发布于 2020-08-21 18:09:08
其他人回答说你应该添加一个null-check,但是Typescript也有一个非null断言,你可以在当然可以属性,以确保该值永远不会为空!运算符添加到语句末尾:
const portalDiv = document.getElementById('#your-element')!;发布于 2021-02-25 04:53:49
所以我不知道是否有人仍然有这个问题,但有一个更简单和直接的解决方案。只需使用以下命令声明模式元素"as“关键词
const modalRoot = document.getElementById("modal-root") as HTMLElement;
这将删除错误。我建议你看看这篇很棒的react-typescript小抄。
https://github.com/typescript-cheatsheets/react
https://stackoverflow.com/questions/63520680
复制相似问题