基本的な使い方
基本的な使い方
// /_/_/_/_/_/_/_/_/_/_
// 子コンポーネント
// /_/_/_/_/_/_/_/_/_/_
import { forwardRef } from "react";
type Props = {
  name: string
}
const Sample = forwardRef<HTMLDivElement, Props>(({ name }, ref) => {
  return <div ref={ref}>
    {name}
  </div>
});
export default Sample;
// /_/_/_/_/_/_/_/_/_/_
// 親コンポーネント
// /_/_/_/_/_/_/_/_/_/_
import { useEffect, useRef } from 'react'
const Home = () => {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!ref.current) return;
    // 子要素のtop取得
    console.log(ref.current.offsetTop);
  }, [])
  
  return <>
    <Sample name="test" ref={ref} />
  </>
});
export default Sample;
forwordRefの型注釈の順番に注意。
forwardRef< propsの型, refをつける要素の型>の順番
// forwardRef<propsの型,refをつける要素の型>の順番にすること
const Sample = forwardRef<Props, HTMLDivElement>(({ name }, ref) => {
  return <div ref={ref}>
    {name}
  </div>
});
Props無しの場合
import { forwardRef } from "react";
// Propsの代わりに"_"
const Sample = forwardRef<HTMLDivElement>((_, ref) => {
  return <div ref={ref}>
    テスト入力
  </div>
});
export default Sample;
自分用にめも
- 複数のrefは使えるか?
- 最新のReactで記述は変わったか?
- ジェネリクスで記述できるか
