首頁 > web前端 > js教程 > 主體

理解 React 中的 useRef Hook

Linda Hamilton
發布: 2024-10-11 10:45:02
原創
197 人瀏覽過

useRefHook 是 React 中的一個重要工具,它允許我們在渲染之間儲存值、直接存取 DOM 元素並避免不必要的重新渲染。它經常與 useStateHook 進行比較,但用途不同。

useRef Hook 是什麼?

useRef Hook 建立在元件渲染之間持續存在的值或 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

何時使用 useRef 而不是 useState

以下是一些 useRefis 比 useState 更適合的場景:

當您需要儲存更新時不需要觸發重新渲染的值時(例如計時器、計數器或追蹤渲染)。
當您需要直接存取或修改 DOM 元素而不導致重新渲染時。

以上是理解 React 中的 useRef Hook的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!