programing

유형 '의 인수HTMlement | null'은 'Element' 유형의 매개 변수에는 할당할 수 없습니다.'null' 유형은 'Element' 유형에 할당할 수 없습니다.ts(2345)

kingscode 2023. 4. 1. 15:02
반응형

유형 '의 인수HTMlement | null'은 'Element' 유형의 매개 변수에는 할당할 수 없습니다.'null' 유형은 'Element' 유형에 할당할 수 없습니다.ts(2345)

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;

그러나 이 오류는 '타입의 인수'로 표시됩니다.HTMlement | null'은 'Element' 유형의 매개 변수에는 할당할 수 없습니다. VScode의 'Element'.ts(2345) 유형에는 'null' 유형을 할당할 수 없습니다.

타이프 스크립트를 사용하고 있습니다.

다른 사용자가 늘체크를 추가해야 한다고 대답했지만 Typescript에는 null이 아닌 어설션도 있습니다.이 어설션은 값을 null로 하는 것이 아니라!명령어 끝에 연산자를 붙입니다.

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

아직 이 문제를 겪고 있는 사람이 있는지 모르겠지만, 보다 쉽고 간단한 해결책이 있습니다.단순히 "as" 키워드를 사용하여 modal 요소를 선언합니다.
const modalRoot = document.getElementById("modal-root") as HTMLElement;그러면 오류가 제거됩니다.리액션 타입의 속임수를 읽어보라고 제안합니다.
https://github.com/typescript-cheatsheets/reacthttpsgithub.com//react

을 사용하여 getElementById지정된 셀렉터와 일치하는 문서 내의 요소를 반환합니다.일치가 발견되지 않으면 기본적으로 null을 반환합니다.

포털 요소를 살펴보겠습니다.

let portalDiv = document.getElementById("portal");

DOM 는 "DOM"을 반환합니다.HTMLElemnt 수 없는 에는 반환한다.null.

, 은 「 」입니다.getElementByIdHTMLElement | null의 두 ReactDom.createPrortal(children: ReactNode, element: HTMLElement, id: string) 말하면HTMLElement를 매겨야 .portalDiv로로 합니다.HTMLElement이치노

「 」는, 「 」는, 「 」라고 하는 에,portalDiv하여 "이 방법"을 할 수 ?null★★★★★★★★★★★★★★★★★★.

let portalDiv = getElementById("portal") as HTMLElement;

, 그럼 에는 이렇게 쓸 수 요.portalDiv에러가 발생하지 않습니다.

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

★★getElementById nullmanager가 될 수 있습니다.따라서 다음과 같이 사용하기 전에 확인만 하면 됩니다.

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

getElementById할 수 있다nullcreatePortal하지 않다null.

포털 div가 존재하는 것을 알고 있는 경우는, 그 것에 관한 코드를 명시해 주세요.

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

TypeScript를 할 수 .| null타입의 일부입니다.또한 이 코드가 더 이상 실행될 때 div가 표시되지 않도록 누군가 변경할 경우 사전 경고를 제공합니다.

이에 대한 최선의 해결책은 null 또는 HTMLDIVElement하나로 만드는 것이 아니라 사용 에서는 DivElement가 현재 비어 있을 수 있다는 것을 타이프 스크립트로 알리려고 하지만 "!" 기호를 사용하는 것만으로 책임집니다.

아래 코드 샘플:

import React, {useEffect} from 'react';
import ReactDOM from 'react-dom';
import './modal-portlet.style.scss';

const modalRoot = document.getElementById('modalRoot');

type Props = {
  children: JSX.Element;
};
const ModalPortlet: React.FC<Props> = ({children}): JSX.Element => {
  const divContainer = window.document.createElement('div');
  divContainer.setAttribute('class', 'modal-container');

  useEffect(() => {
    /**********
     * immediately the component mount append @divContainer as the childNode of @modalRoot in the DOM
     **********/
    modalRoot!.appendChild(divContainer);

    return () => {
      modalRoot!.removeChild(divContainer);
    };
  });

  /************
   * return the createPortal api that takes the children(JSX) and inject it into @divContainer which is already a childNode of @modalRoot
   ************/
  return <>{ReactDOM.createPortal(children, divContainer)}</>;
};

export default ModalPortlet;

ID const element = document.getElementById(auduiId)를 HTMLAudioElement로 하여 getElement의 마지막에 HTMLAudioElemnt로 추가하는 간단한 솔루션이 있습니다.

저도 같은 에러가 발생하고 있기 때문에 몇 가지 다른 방법을 시도했지만, 효과가 있던 것은 null 상태를 처리하고 있습니다. const portalDiv = document.getElementById('portal')!;

node.js를 사용하여 React.js 파일을 Javascript에서 Typescript로 전환하는 경우 index.ts 행 8에 있는 수정 코드가 다음과 같습니다.

const root = ReactDOM.createRoot(document.getElementById('root')!);

빠른 수정은 추가만 하면 됩니다."strictNullChecks": falsetsconfig.json 파일로 이동합니다.

언급URL : https://stackoverflow.com/questions/63520680/argument-of-type-htmlelement-null-is-not-assignable-to-parameter-of-type-el

반응형