React の useRef フックを理解する

Linda Hamilton
リリース: 2024-10-11 10:45:02
オリジナル
198 人が閲覧しました

useRefHook は、レンダリング間で値を保存し、DOM 要素に直接アクセスし、不必要な再レンダリングを回避できるようにする React の重要なツールです。よく useStateHook と比較されますが、目的は異なります。

useRef フックとは何ですか?

useRef フックは、コンポーネントのレンダリング間で保持される値または DOM 要素への参照を作成します。 useRef と useState の主な違いは、useRefvalue を更新しても再レンダリングがトリガーされないことです。これは、特定のシナリオで特に便利です。

  1. 値が変更されても再レンダリングは発生しません。
  2. 変更可能な値を保存するために使用できます。
  3. DOM 要素に直接アクセスするために使用できます。

基本構文

const refContainer = useRef(initialValue);

ログイン後にコピー

例 1: レンダー間での値の保持

import React, { useRef, useEffect } from "react";

function RenderCount() {
  const renderCount = useRef(1);

  useEffect(() => {
    renderCount.current = renderCount.current + 1;
  });

  // Inline styles
  const containerStyle = {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    height: "100vh",
    backgroundColor: "#f4f4f4",
  };

  const headingStyle = {
    fontSize: "2rem",
    color: "#333",
    fontFamily: "Arial, sans-serif",
    backgroundColor: "#fff",
    padding: "20px",
    borderRadius: "8px",
    boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)",
  };

  return (
    <div style={containerStyle}>
      <h1 style={headingStyle}>
        This component has rendered {renderCount.current} times.
      </h1>
    </div>
  );
}

export default RenderCount;

ログイン後にコピー

出力

Understanding the useRef Hook in React

例 2: DOM 要素へのアクセス

import React, { useState, useRef } from "react";

function Timer() {
  const [seconds, setSeconds] = useState(0);
  const intervalRef = useRef(null);

  // Start the timer
  const startTimer = () => {
    if (!intervalRef.current) {
      intervalRef.current = setInterval(() => {
        setSeconds((prevSeconds) => prevSeconds + 1);
      }, 1000);
    }
  };

  // Stop the timer
  const stopTimer = () => {
    clearInterval(intervalRef.current);
    intervalRef.current = null;
  };

  // Reset the timer
  const resetTimer = () => {
    stopTimer();
    setSeconds(0);
  };

  // Inline styles
  const timerContainerStyle = {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    height: "100vh",
    backgroundColor: "#f0f2f5", // Light neutral background
  };

  const timerDisplayStyle = {
    fontSize: "3rem",
    color: "#2c3e50", // Dark blue-gray for a professional look
  };

  const buttonStyle = {
    padding: "10px 20px",
    margin: "10px",
    fontSize: "1rem",
    backgroundColor: "#2980b9", // Professional blue
    color: "white",
    border: "none",
    borderRadius: "5px",
    cursor: "pointer",
    transition: "background-color 0.3s ease-in-out",
  };

  const buttonHoverStyle = {
    backgroundColor: "#1a5276", // Darker shade for hover effect
  };

  return (
    <div style={timerContainerStyle}>
      <h1 style={timerDisplayStyle}>{seconds} seconds</h1>
      <div>
        <button
          style={buttonStyle}
          onClick={startTimer}
          onMouseOver={(e) => (e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor)}
          onMouseOut={(e) => (e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor)}
        >
          Start
        </button>
        <button
          style={buttonStyle}
          onClick={stopTimer}
          onMouseOver={(e) => (e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor)}
          onMouseOut={(e) => (e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor)}
        >
          Stop
        </button>
        <button
          style={buttonStyle}
          onClick={resetTimer}
          onMouseOver={(e) => (e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor)}
          onMouseOut={(e) => (e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor)}
        >
          Reset
        </button>
      </div>
    </div>
  );
}

export default Timer;

ログイン後にコピー

出力

Understanding the useRef Hook in React

useState の代わりに useRef を使用する場合

useState より useRef の方が適切なシナリオをいくつか示します。

更新時に再レンダリングをトリガーする必要のない値を保存する必要がある場合 (タイマー、カウンター、レンダリングの追跡など)。
再レンダリングを行わずに DOM 要素に直接アクセスまたは変更する必要がある場合。

以上がReact の useRef フックを理解するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!