반응에서 ForwardRefExoticComponent와 ForwardRefRenderFunction의 차이점은 무엇입니까?

Oct 07 2020

아이들에게 ref를 전달할 수있는 React 컴포넌트를 작성 중입니다.

함수 구성 요소의 반환 유형에 대해 ForwardRefExoticComponent 및 ForwardRefRenderFunction을 사용할 수 있음을 알았습니다 . 그러나 나는 그들 사이의 차이점이 무엇인지 잘 모르겠습니다.

사용하는 경우 지금까지 ForwardRefExoticComponent을 그동안, 나는 그것을 확장 할 수 있습니다 ForwardRefRenderFunction는 할 수 없습니다? 여기에 내 사례와 관련된 질문을 게시했습니다. ForwardRefRenderFunction으로 forwardRef를 내보내는 방법

누구든지 그들과 그들이하는 일의 차이점을 알고 있다면 저를 도와주세요. React 팀이 그들에 대한 문서가없는 것 같기 때문에 (그러나 그들은 반응 패키지 안에 있습니다)

답변

4 PeterLehnhardt Oct 07 2020 at 14:19

ForwardRefExoticComponent

여기 에서 가져온 정의 는

interface ExoticComponent<P = {}> {
    /**
     * **NOTE**: Exotic components are not callable.
     */
    (props: P): (ReactElement|null);
    readonly $$typeof: symbol;
}

interface NamedExoticComponent<P = {}> extends ExoticComponent<P> {
    displayName?: string;
}

interface ForwardRefExoticComponent<P> extends NamedExoticComponent<P> {
    defaultProps?: Partial<P>;
    propTypes?: WeakValidationMap<P>;
}

당신이 그것을 쓰면 당신은 얻을

interface ForwardRefExoticComponent<P> {
    /**
     * **NOTE**: Exotic components are not callable.
     */
    (props: P): (ReactElement|null);
    readonly $$typeof: symbol;
    displayName?: string;
    defaultProps?: Partial<P>;
    propTypes?: WeakValidationMap<P>;
}

ForwardRefRenderFunction

여기 에서 가져온 정의 는

interface ForwardRefRenderFunction<T, P = {}> {
    (props: PropsWithChildren<P>, ref: ((instance: T | null) => void) | MutableRefObject<T | null> | null): ReactElement | null;
    displayName?: string;
    // explicit rejected with `never` required due to
    // https://github.com/microsoft/TypeScript/issues/36826
    /**
     * defaultProps are not supported on render functions
     */
    defaultProps?: never;
    /**
     * propTypes are not supported on render functions
     */
    propTypes?: never;
}

차이점

  • ForwardRefRenderFunction지원하지 않는 propTypes및 defaultProps반면, ForwardRefExoticComponent않습니다.
  • ForwardRefExoticComponent$$typeof유형 의 추가 멤버 가 있습니다.symbol
  • 의 호출 서명 ForwardRefRenderFunction얻어 props멤버 포함해야 오브젝트 children의 콜 사인 반면, 및 파라미터로서 REF 객체 ForwardRefExoticComponent만이 소품 파라미터 등 임의의 형상의 목적 걸린다.

좀 더 생각

이 두 정의의 상호 작용은 함수 정의forwardRef 에서 가장 잘 보입니다 .

function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;

또한 두 정의의 큰 차이점은 ForwardRefExoticComponent(모든 이국적인 구성 요소와 마찬가지로) 함수 구성 요소가 아니라 실제로 렌더링 할 때 특별히 처리되는 객체라는 것입니다. 따라서 코멘트

참고 : 이국적인 구성 요소는 호출 할 수 없습니다.

그리고 어떤 이유로 이러한 이국적인 구성 요소는 어떤 곳에서 필요합니다.