useRefHook 是 React 中的一個重要工具,它允許我們在渲染之間儲存值、直接存取 DOM 元素並避免不必要的重新渲染。它經常與 useStateHook 進行比較,但用途不同。
useRef Hook 是什麼?
useRef Hook 建立在元件渲染之間持續存在的值或 DOM 元素的參考。 useRef 和 useState 之間的主要區別在於,更新 useRefvalue 不會觸發重新渲染,這在某些場景下特別有用。
- 當其值改變時,不會導致重新渲染。
- 它可用於儲存可變值。
- 可以用來直接存取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;
輸出
範例 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 id="seconds-seconds">{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中文網其他相關文章!

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載
最受歡迎的的開源編輯器