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?

More than 3 years have passed since last update.

基礎から学ぶReact/React Hooks学習メモ 5-4 useRef

Posted at

React Hooksを基礎から理解する 5-4 useRef

参考
基礎から学ぶReact/React Hooks

useRefとは

  • 要素の参照を行う。主にDOMへのアクセスに利用される。
  • コンポーネント内において、変数に値を保持することができる。
  • 値を更新してもコンポーネントが再レンダリングされることはない。→ useState()と異なる点
  • インポート
import React, { useRef } from "react";
  • useRefの基本構文。関数コンポーネントのトップレベルで宣言する。
const refObjct = useRef(初期値);
  • refObjectのcurrentプロパティの値は1000になる。
const refObject = useRef(1000);
console.log(refObject.current); // 1000

useRefの利用例(useStateとの比較)

  • ref属性で、inputRefObjectとinput要素を関連付ける
  • ボタンをクリックすると、inputRefObject.current.focus()でテキストボックスにフォーカスする。
  • useStateのほうに文字を入力すると「レンダリング!」のログが出るが、useRefのほうは出ない

image.png

import React, { useState, useEffect, useRef } from "react";
import "./styles.css";

const SampleComponent = () => {
  const inputRefObject = useRef(null);

  const [inputValue, setInputValue] = useState("");

  const handleClick = () => {
    inputRefObject.current.focus();
  };

  // useEffectの第2引数がない場合、レンダリングされるたびに呼び出される
  useEffect(() => {
    console.log("レンダリング!");
  });

  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  // ref属性で、inputRefObjectとinput要素を関連付ける
  return (
    <>
      useState: <input onChange={handleChange} type="text" />
      <br />
      useRef: <input ref={inputRefObject} type="text" />
      <button onClick={handleClick}>入力エリアをフォーカス</button>
    </>
  );
};

export default function App() {
  return <SampleComponent />;
}

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?