잡동사니

반응형

질문

 

자식을 반복하고 div로 감싸는 component가 있습니다. 제외를 추가하려고하지만 자식이 ReactElement 인지 확인할 수없는 문제가 발생합니다 ( React.ReactChild 는 문자열 또는 숫자이므로 유형이 없을 수 있습니다).

아래의 방법을 시도해 보았습니다 : " 'ReactElement'는 유형만을 참조하지만 여기서는 값으로 사용되고 있습니다." 'ReactChild'유형에는 'type'속성이 없습니다. '

올바른 방향으로 나를 가리키는 도움을 주시면 대단히 감사하겠습니다.

 {React.Children.map(children, (child: React.ReactChild) => {
        /**
         * Exclude these components from being
         * wrapped by the item wrapper.
         */
        if (child instanceof React.ReactElement<any> && child.type === Divider) {
          return child;
        }

        if (child) {
          return <div className="l-spacer__item">{React.cloneElement(child as React.ReactElement<any>)}</div>;
        }

        return null;
      })}

 

답변1

 

child instanceof React.ReactElement<any>

React.ReactElement 가 값이 아니기 때문에 유효하지 않습니다. 인터페이스입니다. 인터페이스는 단지 유형이며 class와 달리 해당 값이 없습니다. 모든 유형이 지워집니다. runtime 표현이 없습니다.

또한 JavaScript의 instanceof 가 사용되며 다음과 같이 이해해야합니다.

value instanceof anotherValue

이것은 구문 상 유사한 언어에서 온 사람들을 비슷한 이름의 연산자와 혼동하지만 오른쪽 피연산자는 유형입니다. JavaScript에서 두 피연산자는 항상 값입니다.

특정 검사를 수행하려면 코드를

if (typeof child !== 'string' && typeof child !== 'number' && child.type === Divider) {
  return child;
}

React.ReactChild 유형이 다음과 같이 정의되어 있기 때문에 작동합니다.

React.ReactElement | React.ReactText;

React.ReactText 는 다음과 같이 정의됩니다.

string | number

이러한 경우를 제거함으로써 언어는 type 속성이있는 세 번째 가능한 통합 사례 인 React.ReactElement 와 일치한다는 것을 알게됩니다.

 

 

 

 

 

출처 : https://stackoverflow.com/questions/63064972/check-if-a-component-is-an-instance-of-react-reactelementany-in-a-child-map

반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band