code

forwardRef: 속성 'ref'가 'IntrinsicAttributes' 유형에 있는 일반 오류가 없습니다.

starcafe 2023. 6. 7. 23:02
반응형

forwardRef: 속성 'ref'가 'IntrinsicAttributes' 유형에 있는 일반 오류가 없습니다.

generics와 함께 forwardRef를 사용하면 다음과 같이 됩니다.Property 'children' does not exist on type 'IntrinsicAttributes'또는Property 'ref' does not exist on type 'IntrinsicAttributes'.

https://codesandbox.io/s/react-typescript-0dt6d?fontsize=14

위의 CodeSandbox 링크에 있는 관련 코드는 다음과 같이 복제됩니다.

interface SimpleProps<T extends string>
  extends React.HTMLProps<HTMLButtonElement> {
  random: T;
}

interface Props {
  ref?: React.RefObject<HTMLButtonElement>;
  children: React.ReactNode;
}

function WithGenericsButton<T extends string>() {
  return React.forwardRef<HTMLButtonElement, Props & SimpleProps<T>>(
    ({ children, ...otherProps }, ref) => (
      <button ref={ref} className="FancyButton" {...otherProps}>
        {children}
      </button>
    )
  );
}

() => (
  <WithGenericsButton<string> ref={ref} color="green">
    Click me! // Errors: Property 'children' does not exist on type 'IntrinsicAttributes'
  </WithGenericsButton>
)

잠재적인 해결책이 여기에 제시되지만 이 맥락에서 구현하는 방법은 확실하지 않습니다. https://github.com/microsoft/TypeScript/pull/30215 (https://stackoverflow.com/a/51898192/9973558) 에서 확인할 수 있습니다.

그래서 여기서 가장 큰 문제는 당신이 그 결과를 돌려준다는 것입니다.React.forwardRef렌더 함수에 대한 올바른 반환 형식이 아닌 렌더 유형이 아닙니다.ForwardRef 결과를 자체 구성 요소로 정의한 다음 WithGenericsButton 내에서 다음과 같이 상위 구성 요소로 렌더링해야 합니다.

import * as React from "react";

interface SimpleProps<T extends string> {
  random: T;
}

interface Props {
  children: React.ReactNode;
  color: string;
}

function WithGenericsButton<T extends string>(
  props: Props & SimpleProps<T> & { ref: React.Ref<HTMLButtonElement> }
) {
  type CombinedProps = Props & SimpleProps<T>;
  const Button = React.forwardRef<HTMLButtonElement, CombinedProps>(
    ({ children, ...otherProps }, ref) => (
      <button ref={ref} className="FancyButton" {...otherProps}>
        {children}
      </button>
    )
  );
  return <Button {...props} />;
}

const App: React.FC = () => {
  const ref = React.useRef<HTMLButtonElement>(null);
  return (
    <WithGenericsButton<string> ref={ref} color="green" random="foo">
      Click me!
    </WithGenericsButton>
  );
};

만약 당신이 그것을 샌드박스나 놀이터에 두면 당신은 그것을 볼 수 있을 것입니다.props이제 를 포함하여 올바르게 입력되었습니다.random의 버팀목.T

문제는 다음 기능 때문입니다.

function WithGenericsButton<T extends string>() {
  return React.forwardRef<HTMLButtonElement, Props & SimpleProps<T>>(
    ({ children, ...otherProps }, ref) => (
      <button ref={ref} className="FancyButton" {...otherProps}>
        {children}
      </button>
    )
  );
}

WithGenericsButton구성 요소가 아닙니다.구성 요소를 반환하는 js 함수입니다. TS는 기본적으로 다음과 같이 말합니다. 헤이 구성 요소WithGenericsButton(하나로 사용하고 있기 때문에)라는 소품이 없습니다.children그리고 그것은 옳습니다, 그렇지 않습니다.

렌더링할 수 있는 구성 요소를 얻으려면 다음과 같은 작업을 수행해야 합니다.const StringButton = WithGenericsButton<string>();

당신의 질문을 이해할 수 있는 다른 좋은 방법을 찾았습니다.이런 거.

export interface Props = {
   ...yourPropsHere;
};

export interface CompoundedComponent extends React.ForwardRefExoticComponent<Props & React.RefAttributes<HTMLInputElement>> {
   yourStaticFunctionOrSomethingLikeThat: () => void;
}

const Component = React.forwardRef<HTMLInputElement, Props>((props, ref) => (
    <input ref={ref} {...props} />
)) as CompoundedComponent;

Component.yourStaticFunctionOrSomethingLikeThat = () => {};

언급URL : https://stackoverflow.com/questions/57750777/generics-error-with-forwardref-property-ref-does-not-exist-on-type-intrinsic

반응형