programing

React 상태 비저장 구성 요소의 TypeScript 반환 유형은 무엇입니까?

mailnote 2023. 3. 22. 21:49
반응형

React 상태 비저장 구성 요소의 TypeScript 반환 유형은 무엇입니까?

반품 타입은 어떻게 되나요?

const Foo
  : () => // ???
  = () => (
    <div>
      Foobar
    </div>
  )

StatelessComponentHooks API를 도입한 후 항상 상태 비저장 상태가 아니므로 이 답변에서 언급된 유형은 사용되지 않습니다.

함수 구성요소가 유형입니다.React.FunctionComponent가명도 있어요React.FC일을 짧게 마무리 짓기 위해서요

여기에는 하나의 필수 속성, 즉 함수가 있으며, 이 함수는 다음을 반환합니다.ReactElement또는null. 다음과 같은 몇 가지 옵션 속성이 있습니다.propTypes,contextTypes,defaultProps그리고.displayName.

다음은 예를 제시하겠습니다.

const MyFunctionComponent: React.FC = (): ReactElement => {
  return <div>Hello, I am a function component</div>
}

@types/react 16.8.24 의 타입은 다음과 같습니다.

type FC<P = {}> = FunctionComponent<P>;

interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>, context?: any): ReactElement | null;
    propTypes?: WeakValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}
interface ISomeCoolInterface {
   some: 'string';
   cool: 'string';
   props: 'string' 
}    

const SomeCoolComponent
    : React.FC<ISomeCoolInterface> 
    = ({ some, cool, props }): JSX.Element => {
        return <SomeCoolComponent>{some, cool, props}</SomeCoolComponent>      
    }

여기서 중요한 것은 반품 타입입니다.JSX.Element

를 사용하는 경우function키워드, 최적의 리턴 타입은JSX.Element | null.

현재로서는 JSX 결과로 직접 반환할 수 있는 두 가지 유형만 있으므로 JSXName을 약어로 사용하고 있습니다.

type JSXNode = JSX.Element | null;

편집: 최종적으로 반응하는 것처럼 보입니다.ReactNode는 JSX에 대한 반환 유형이지만 현재 불가능합니다. (참조)


배경:

이 답변 중 가장 일반적인 현대의 사례를 다루는 것은 없습니다. 즉, 요소를 반환하는 함수가 있다는 것입니다.이것은 어떤 타입을 반환해야 합니까?

function MyComponent(): SomeTypeHere {
  return <>...</>;
}

컴포넌트를 숨기는 권장 방법은 null을 반환하는 것이기 때문에 어떤 반환 유형이 깨끗한지 알 수 없습니다.JSX 라고 입력합니다.Element |null은 어디에나 존재하거나 이러한 커스텀유형을 만들 필요는 없을 것 같습니다.정의되지 않은 ReactNode는 JSX로 반환할 수 없기 때문에 작동하지 않습니다.

전반적으로 가장 좋은 반품 유형은 다음과 같습니다.JSX.Element | null이 타입은 Return 타입입니다.FC를 사용하지 않을 경우 사용되는 유형function키워드:

const MyComponent: FC = () => { <>...</> }

올바른 반환 유형은 다음과 같습니다.ReactElement<P>, 그러나 더 나은 방법은React.StatelessComponent<P>이것처럼.

const Foo
  : React.StatelessComponent<{}>
  = () => (
    <div>
      Foobar
    </div>
  )

그리고 제가 덧붙이고 싶은 것은.SFCStateless Functional Component(스테이트리스 기능 컴포넌트)를 나타냅니다.

const Foo
  : React.SFC<{}>
  = () => (
    <div>
      Foobar
    </div>
  )

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts 를 참조해 주세요.

각 JSX 요소는 React.createElement(컴포넌트, 소품, ...자녀)를 호출하기 위한 구문설탕일 뿐입니다.

function createElement<P extends DOMAttributes<T>, T extends Element>(
    type: string,
    props?: ClassAttributes<T> & P,
    ...children: ReactNode[]): DOMElement<P, T>;

그래서...DOMElement<P, T>

언급URL : https://stackoverflow.com/questions/44133420/what-is-the-typescript-return-type-of-a-react-stateless-component

반응형