ReactのForwardRefExoticComponent
というのを見かけたので調べた
ForwardRefExoticComponent
は、React.forwardRef
を使用して作成されたコンポーネントの型を表す
Reactコンポーネントでどのように使用されるか
React では、ForwardRefExoticComponent
は主に、親コンポーネントが子コンポーネントの DOM ノードに直接アクセスできるようにするために使用される
これは、フォーカス、選択、またはアニメーションを管理する場合に特に便利
このインターフェースにより、必要に応じて DOM ノードへの直接アクセスを犠牲にすることなく、コンポーネントが構成可能かつ再利用可能であることが保証される
型の定義
interface ForwardRefExoticComponent<P> extends NamedExoticComponent<P> { defaultProps?: Partial<P> | undefined; propTypes?: WeakValidationMap<P> | undefined; }
使い方の流れ
React.forwardRef
を使用して関数コンポーネントを作成する。ref
とprops
を受け取るように設計する。ForwardRefExoticComponent
型が自動的に適用される。
使用例
import React, { forwardRef, useRef } from 'react'; type ButtonProps = { label: string; }; const CustomButton = forwardRef<HTMLButtonElement, ButtonProps>( ({ label }, ref) => { return <button ref={ref}>{label}</button>; } ); const ParentComponent = () => { const buttonRef = useRef<HTMLButtonElement>(null); const handleClick = () => { if (buttonRef.current) { buttonRef.current.focus(); } }; return ( <div> <CustomButton ref={buttonRef} label="Click Me" /> <button onClick={handleClick}>Focus Button</button> </div> ); };