Memahami penggunaanRef Hook dalam React

Linda Hamilton
Lepaskan: 2024-10-11 10:45:02
asal
198 orang telah melayarinya

useRefHook ialah alat penting dalam React yang membolehkan kami menyimpan nilai antara pemaparan, mengakses terus elemen DOM dan mengelakkan pemaparan semula yang tidak perlu. Ia sering dibandingkan dengan useStateHook tetapi mempunyai tujuan yang berbeza.

Apakah kegunaanRef Hook?

UseRef Hook mencipta rujukan kepada nilai atau elemen DOM yang berterusan antara pemaparan komponen. Perbezaan utama antara useRefand useState ialah mengemas kini useRefvalue tidak mencetuskan pemaparan semula, yang boleh berguna terutamanya dalam senario tertentu.

  1. Ia tidak menyebabkan pemaparan semula apabila nilainya berubah.
  2. Ia boleh digunakan untuk menyimpan nilai boleh ubah.
  3. Ia boleh digunakan untuk mengakses terus elemen DOM.

Sintaks Asas

const refContainer = useRef(initialValue);

Salin selepas log masuk

Contoh 1: Nilai Berterusan Antara Render

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;

Salin selepas log masuk

Output

Understanding the useRef Hook in React

Contoh 2: Mengakses Elemen 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;

Salin selepas log masuk

Output

Understanding the useRef Hook in React

Bila Gunakan useRef Daripada useState

Berikut ialah beberapa senario di mana useRefis lebih sesuai daripada useState:

Apabila anda perlu menyimpan nilai yang tidak perlu mencetuskan pemaparan semula apabila dikemas kini (mis., pemasa, pembilang atau pemaparan penjejakan).
Apabila anda perlu mengakses terus atau mengubah suai elemen DOM tanpa menyebabkan pemaparan semula.

Atas ialah kandungan terperinci Memahami penggunaanRef Hook dalam React. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!