【React+TypeScript】React Hooks useImperativeHandle의 샘플
4219 단어 ReactTypeScript후크

TypeScript에서
useImperativeHandle 사용하는 예제.부모의 컴퍼넌트로부터, 아이로 정의한 메소드를 호출하는 경우에 사용합니다.
FancyInput.tsx
import React, { useRef, useImperativeHandle, forwardRef } from "react";
// 公開したいメソッドの定義
interface Handler {
setFocus(): void;
}
// 公開したいメソッドを持つコンポーネントの定義
// プロパティを追加する場合は、forwardRef<Handler, Props>と定義する。
const FancyInput = forwardRef<Handler>((props, ref) => {
const inputRef = useRef({} as HTMLInputElement);
useImperativeHandle(ref, () => {
return {
setFocus() {
inputRef.current.focus();
}
};
});
return <input ref={inputRef} type="text" />;
});
// コンポーネントの使い方
const App = () => {
const ref = useRef({} as Handler);
return (
<>
<FancyInput ref={ref} />
<button
onClick={() => {
ref.current.setFocus();
}}
>
click
</button>
</>
);
};
Reference
이 문제에 관하여(【React+TypeScript】React Hooks useImperativeHandle의 샘플), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/otanu/items/994fdf9d8fb7327d41d5텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)