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中文网其他相关文章!