“React ForwardRef UsyMerativeHandle TypeScript” Ответ

React ForwardRef UsyMerativeHandle TypeScript

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);

/* 
and then use React utility ElementRef, TypeScript
can infer exact ref type of your component
*/
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} />
  );
};
florinrelea

React ForwardRef TypeScript

type MyProps = {
  name: string;
}

const CustomInput = forwardRef<HTMLInputElement, MyProps>(props) => {
  // access your props and ref here
}
peachmangopie

Ответы похожие на “React ForwardRef UsyMerativeHandle TypeScript”

Вопросы похожие на “React ForwardRef UsyMerativeHandle TypeScript”

Больше похожих ответов на “React ForwardRef UsyMerativeHandle TypeScript” по TypeScript

Смотреть популярные ответы по языку

Смотреть другие языки программирования