ForwardRefRenderFunction으로 forwardRef를 내보내는 방법

Oct 06 2020

UI 라이브러리에 속하는 구성 요소가 있는데 입력 구성 요소라고 부릅니다. 이 라이브러리를 사용하여 Input을 호출 할 때 호출 할 수있는 유형이 많이 있습니다. 예를 들면

<Input />
<Input.TextArea />
<Input.Search />

이제이 입력 구성 요소에 래퍼를 작성하고 싶으므로 다음과 같이 작성합니다.

type InputWrapperComponent = FC<InputProps> & {
  Search: typeof Input.Search;
  TextArea: typeof Input.TextArea;
};

const InputWrapper: InputWrapperComponent = (props) => {
  // make some minor changes here
}

InputWrapper.Search = Input.Search;
InputWrapper.TextArea = Input.TextArea;
export default InputWrapper;

에서 index.tsx

export { default as InputWrapper } from './input';

그런 다음 다음과 같이 사용할 수 있습니다.

<InputWrapper />. --> Works
<InputWrapper.TextArea />. --> Works
<InputWrapper.Search />. --> Works

하지만 이렇게 하면 원래 UI 라이브러리의 ref 메서드 (예 :)를 사용할 수 없습니다 inputRef.current.focus(). 그래서 저는 forwardRef 와 ForwardRefRenderFunction을 이렇게 사용 합니다.

type InputWrapperComponent = ForwardRefRenderFunction<HTMLInputElement, InputProps> & {
  Search: typeof Input.Search;
  TextArea: typeof Input.TextArea;
};

const InputWrapper: InputWrapperComponent = (props, ref) => {
  // make some minor changes here and add the ref to the input
}

InputWrapper.Search = Input.Search;
InputWrapper.TextArea = Input.TextArea;
export default forwardRef(InputWrapper);

이것으로 변경하면 참조를 원래 UI 라이브러리에 전달하고 원래 메서드를 사용할 수 있습니다. 그러나 지금 내 문제는 forwardRef 및 ForwardRefRenderFunction으로 변경하면 더 이상 TextArea 및 Search를 호출 할 수 없다는 것입니다.

<InputWrapper />. --> Works
<InputWrapper.TextArea />. --> Error
<InputWrapper.Search />. --> Error

이것은 오류입니다.

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

누구든지 이것에 대한 지침을 줄 수 있습니까? 감사

답변

1 PeterLehnhardt Oct 07 2020 at 07:23

당신이하는 일은 :

  1. 함수 InputWrapper를 유형으로 정의InputWrapperComponent
  2. 정의 Search및 TextArea구성원으로InputWrapper
  3. 다음을 사용하여 참조 전달 구성 요소 만들기 forwardRef

문제는 forwardRef완전히 새로운 구성 요소 를 생성하고 이전에 정의 된 일부 하위 구성 요소가 있었는지 상관하지 않는다는 것입니다. 그들은 그냥 버려지고 해당 멤버가 정의되지 않은 오류가 발생합니다.

따라서 실제로 이동하는 방법은 다음과 같습니다.

  1. 함수 InputWrapper를 유형으로 정의InputWrapperComponent
  2. 다음을 사용하여 참조 전달 구성 요소 만들기 forwardRef
  3. 정의 Search및 TextArea새로운 심판 전달 구성 요소의 구성원으로
1 JakeLam Oct 07 2020 at 05:32

ForwardRefRenderFunction 대신 ForwardRefExoticComponent를 사용하게됩니다.

type InputWrapperComponent = React.ForwardRefExoticComponent<
  React.PropsWithoutRef<InputProps> & React.RefAttributes<HTMLInputElement>
> & {
  Search: typeof Input.Search;
  TextArea: typeof Input.TextArea;
  Password: typeof Input.Password;
};

그러나 나는 그들 사이의 차이점이 무엇인지 잘 모르겠습니다.

업데이트 : 피터의 답변을 확인 해주세요.

둘 의 차이점은 무엇입니까? 여기에서 그의 대답을 확인하십시오 : 반응에서 ForwardRefExoticComponent와 ForwardRefRenderFunction의 차이점은 무엇입니까?