Typescript和React编译错误

时间:2019-06-21 05:14:02

标签: reactjs typescript

对于el和modalRoot类型,我遇到2个打字错误。我应该如何声明el和modalRoot来消除打字稿错误?

interface IModal {
  closeModal: () => {};
  title: string;
  children: ReactNode
}

const Modal = (props: IModal) => {
const {  closeModal, title, children } = props;
let el = null;
const modalRoot = document.getElementById('modal-root');

useEffect(() => {
  el = React.createElement('div');
  modalRoot.appendChild(el);
  return () => modalRoot.removeChild(el);
}, []);
....
}

1 个答案:

答案 0 :(得分:0)

您只需在钩子中添加一个if语句:

useEffect(() => {
  el = React.createElement('div');
  if (!!el && !!modalRoot) {
    modalRoot.appendChild(el);
    return () => modalRoot.removeChild(el);
  }
}, []);