0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React/TS】forwordRefの使い方メモ

Last updated at Posted at 2024-12-07

基本的な使い方

基本的な使い方

// /_/_/_/_/_/_/_/_/_/_
// 子コンポーネント
// /_/_/_/_/_/_/_/_/_/_
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で記述は変わったか?
  • ジェネリクスで記述できるか
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?