useRefHook 是 React 中的一個重要工具,它允許我們在渲染之間儲存值、直接存取 DOM 元素並避免不必要的重新渲染。它經常與 useStateHook 進行比較,但用途不同。
useRef Hook 是什麼?
useRef Hook 建立在元件渲染之間持續存在的值或 DOM 元素的參考。 useRef 和 useState 之間的主要區別在於,更新 useRefvalue 不會觸發重新渲染,這在某些場景下特別有用。
基本文法
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;
輸出
範例 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;
輸出
何時使用 useRef 而不是 useState
以下是一些 useRefis 比 useState 更適合的場景:
當您需要儲存更新時不需要觸發重新渲染的值時(例如計時器、計數器或追蹤渲染)。
當您需要直接存取或修改 DOM 元素而不導致重新渲染時。
以上是理解 React 中的 useRef Hook的詳細內容。更多資訊請關注PHP中文網其他相關文章!