sourcetip

TypeScript에서 컴포넌트 유형 반응

fileupload 2023. 2. 13. 20:38
반응형

TypeScript에서 컴포넌트 유형 반응

TypeScript에서 반응 컴포넌트의 유형을 올바르게 설명하는 방법은 무엇입니까?반응 성분을 반환하는 함수가 있다고 가정해 봅시다.기능:

const getTabContent: () => ReactElement = () => {
  switch (tab) {
    case 1:
      return <Images images={images} onSelect={onSelect}/>;
    default:
      return <Search onSelect={onSelect}/>;
  }
};

여기서는 반환 유형을 ReactElement라고 표현합니다만, 올바른 것인지, 아니면 ReactComponentElement라고 표현해야 하는지, 아니면 완전히 다른 방식으로 설명해야 하는지 궁금합니다.또한 두 유형 모두 제네릭이며, 둘 중 하나가 맞다면 어떻게 자세히 설명할 수 있습니까?

UPD ReactElement는 FC(Function Component)가 반환하기 때문에 적합한 것 같습니다.

기능 컴포넌트의 올바른 유형은 다음과 같습니다.React.FunctionComponent또는React.FC숏컷 에일리어스입니다

import React, { FC } from 'react';

const getTabContent: FC = () => {
  switch (tab) {
    case 1:
      return <Images images={images} onSelect={onSelect}/>;
    default:
      return <Search onSelect={onSelect}/>;
  }
};

FC를 입력하기만 하면 됩니다.children의 재산props액세스 할 수 있도록 기능 컴포넌트의 인수를 지정합니다.

const SomeComponent: FC = ({ children }) => (
  <div className="hello">{children}</div>
);

FC는 범용 타입이므로 컴포넌트에 소품을 추가할 수 있습니다.

interface SomeComponentProps {
  foo: string;
}

const SomeComponent: FC<SomeComponentProps> = ({ children, foo }) => (
  <div className={`Hello ${foo}`}>{children}</div>
);

편집: 리액트 18 업데이트

리액트 18 이후로FC추가되지 않음children암묵적으로 제안하고 명시적인 방법을 제공합니다.PropsWithChildren제네릭스형

예:

type SomeComponentProps = { a: string };

const SomeComponent: FC<SomeComponentProps> = ({ a }) => <div>{a}</div>;

// This will fail when using the following expression
<SomeComponent>Hey I'm a child</SomeComponent>

자녀와 함께 사용:

type ComponentWithChildrenProps = PropsWithChildren<{ a: string }>;

const ComponentWithChildrenProps: FC<ComponentWithChildrenProps> = ({
  a,
  children
}) => <div>{a} and {children}</div>

이 때문에,children좀 더 엄격한 버팀목입니다.

type StrictCompProps = { children: string };

const StrictComp: FC<StrictCompProps> = ({ children }) => <div>{children}</div>;

// This will fail
<StrictComp><span>hey</span></StrictComp>

Function Component를 클래스 Component와 함께 사용하려면 다음을 사용하십시오.React.ComponentType

React에 내장된 정의를 고려하면 다음과 같습니다.

type PropsWithChildren<P> = P & {
    children?: React.ReactNode;
}

사용하고 있다React.ReactNode. 이것은 다음과 같이 정의됩니다.

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

TypeScript에는 강력한 유형 추론이 포함되어 있습니다.그냥 대부분의 장소에서 사용하세요.세분화된 인터페이스가 필요한 것은 최상위 컴포넌트뿐입니다.

예를 들어, 여기서 결과 유형은 JSX로 계산됩니다.요소

const getTabContent = ({ tab, onSelect }: { tab: number, onSelect: (ev: React.SyntheticEvent) => void }) => {
  switch (tab) {
    case 1:
      return <Image src="123"/>;
    default:
      return <Search onSelect={onSelect}/>;
  }
};

가장 좋은 선택은ComponentType기능 컴포넌트에 엄격한 경우 다음 컴포넌트를 사용할 수 있습니다.FC클래스 컴포넌트 타입과 기능 컴포넌트 타입의 서포트가 필요한 경우도 있습니다(즉, 프로포트가 기능 컴포넌트 또는 클래스 컴포넌트를 필요로 하는 프로포넌트 타입의 정의).

권장되는 방법은ComponentType유형 정의(예: ProopTypes) 및FC반환 유형 등을 정의하는 경우

참고로 다음과 같은 정의가 있습니다.ComponentType,FC타이프로

type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;
type FC<P = {}> = FunctionComponent<P>;

유형을 사용하여 구성요소를 정의하고 다른 위치에서 사용하는 간단한 샘플:

1단계: 다음과 같이 컴포넌트를 정의합니다.

import React from "react";

const HomePage: React.FC = () => {
  return (
    <div>
      <h3>Home Page</h3>
    </div>
  );
};

export default HomePage;

스텝 2: 기능 컴포넌트의 유형을 설명하기 위한 인터페이스를 정의합니다.

export interface IRouteDto {
    id: number,
    path: string,
    faTitle: string
    element: React.FC,
}

3단계: 인터페이스를 쉽게 사용:

export const routes: IRouteDto[] = [
    {id: 1, path:"/", faTitle: "خانه", element:HomePage}
    {id: 2, path:"/about", faTitle: "درباره ما", element:AboutPage},
    {id: 3, path:"/contact-us", faTitle: "تماس با ما", element:ContactUsPage},
]

React.ReactNode반응하다

언급URL : https://stackoverflow.com/questions/56947690/react-component-type-in-typescript

반응형