IT이야기

React.useImperativeHandle()로 유형을 선언하십시오.

cyworld 2022. 3. 27. 14:22
반응형

React.useImperativeHandle()로 유형을 선언하십시오.

function App(){
  const cntEl:any = React.useRef(null);  // I don't know what type should be here.
  React.useEffect(()=>{
    if(cntEl.current){ cuntEl.current.start() }
  }, []);
  return <Countdown ref={cntEl} />
}
const Countdown = React.forwardRef((props,ref) => {
  React.useImperativeHandle(ref, ()=>({
    start() {
      alert('Start');
    }
  });
  return <div>Countdown</div>
});

부모 구성 요소에서 자식 메서드를 사용하려고 하는 방법ref그리고React.useImperativeHandle().

그것은 잘 작동한다.

하지만 나는 만족하지 못한다.const cntEl:any.

나는 사용을 피하는 많은 방법들이 있다고 믿는다.any나는 모른다.

나는 그냥 다른 타입으로 바꿀 수 있는 타입이 필요하다.any.

편집됨

내가 볼 수 있다.(property) React.MutableRefObject<null>.current: null내가 에 맴돌릴 때.cntEl.current

형식 정의를 더 명시적으로 사용하는 것이 좋다.

예를 들어, 반응 DT를 사용하여 참조 이국적인 구성 요소를 정의하십시오.ForwardRefRenderFunction대신에FC.

type CountdownProps = {}
    
type CountdownHandle = {
  start: () => void,
}
    
const Countdown: React.ForwardRefRenderFunction<CountdownHandle, CountdownProps> = (
  props,
  forwardedRef,
) => {
  React.useImperativeHandle(forwardedRef, ()=>({
    start() {
      alert('Start');
    }
  });

  return <div>Countdown</div>;
}

export default React.forwardRef(Countdown);

그런 다음 반응 유틸리티를 사용하십시오.ElementRef, TypeScript에서 구성 요소의 정확한 참조 유형을 유추할 수 있음

const App: React.FC = () => {
  // this will be inferred as `CountdownHandle`
  type CountdownHandle = React.ElementRef<typeof Countdown>;

  const ref = React.useRef<CountdownHandle>(null); // assign null makes it compatible with elements.

  return (
    <Countdown ref={ref} />
  );
};

합격된 답변은 과소포장이니, 그냥 활자 신고만 하면 된다.

내게는 이렇게 될 것이다.

// Countdown.tsx

export type CountdownHandle = {
  start: () => void;
};

type Props = {};

const Countdown = React.forwardRef<CountdownHandle, Props>((props, ref) => {
  React.useImperativeHandle(ref, () => ({
    // start() has type inferrence here
    start() {
      alert('Start');
    },
  }));

  return <div>Countdown</div>;
});
// The component uses the Countdown component

import Countdown, { CountdownHandle } from "./Countdown.tsx";

function App() {
  const countdownEl = React.useRef<CountdownHandle>(null);

  React.useEffect(() => {
    if (countdownEl.current) {
      // start() has type inferrence here as well
      countdownEl.current.start();
    }
  }, []);

  return <Countdown ref={countdownEl} />;
}

타이핑할 필요가 없다.cntEl로서any. 또한 Countdown을 의 유형 일반 파라미터로 사용할 수 있다.useRef

const cntEl = React.useRef<Countdown>(null);

참조URL: https://stackoverflow.com/questions/62210286/declare-type-with-react-useimperativehandle

반응형