編寫一個自定義鉤以跟踪窗口大小並更改組件時更新。
為了創建一個自定義掛鉤,該掛鉤跟踪窗口大小並在變化時更新組件,我們將在React中使用useState
和useEffect
鉤。這是實現此鉤子的分步方法:
<code class="javascript">import { useState, useEffect } from 'react'; function useWindowSize() { // Initialize state with undefined width/height so server-side render works const [windowSize, setWindowSize] = useState({ width: undefined, height: undefined, }); useEffect(() => { // Handler to call on window resize function handleResize() { // Set window width/height to state setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); } // Add event listener window.addEventListener("resize", handleResize); // Call handler right away so state gets updated with initial window size handleResize(); // Remove event listener on cleanup return () => window.removeEventListener("resize", handleResize); }, []); // Empty array ensures that effect is only run on mount return windowSize; } export default useWindowSize;</code>
此自定義掛鉤( useWindowSize
使用useState
鉤子來管理窗口大小的狀態和useEffect
掛鉤,以設置和清理窗口調整大小事件的事件偵聽器。掛鉤返回當前窗口大小,可用於導入並使用此鉤的任何組件中。
如何實現自定義鉤以實時監視窗口尺寸的變化?
要實現一個自定義鉤以實時監視窗口大小的變化,請按照以下步驟:
-
導入必要的鉤子:首先從React導入
useState
和useEffect
,因為這些對於管理狀態和副作用至關重要。 -
初始化狀態:使用
useState
以width
和height
設置為undefined
狀態初始化狀態。這允許在無法使用window
的服務器端渲染期間正確工作。 -
創建一個大小處理程序:定義一個功能
handleResize
,該函數處理程序可以使用當前window.innerWidth
和window.innerHeight
更新狀態。 Innerheight。 -
設置事件偵聽器:內部
useEffect
,將事件偵聽器添加到resize
大小事件的window
對像中。每當調整窗口大小時,該偵聽器都會調用handleResize
。 -
初始呼叫:立即在
useEffect
中handleResize
以設置初始窗口大小。 -
清理:從
useEffect
返回清理功能,該功能在組件卸下或效果再次運行時刪除事件偵聽器。 -
返回狀態:最後,從鉤子返回
windowSize
狀態,以便在組件中使用。
這種方法可確保鉤子實時更新窗口大小並適當清理資源。
根據窗口大小,使用自定義鉤有效更新組件的最佳實踐是什麼?
使用自定義鉤子根據窗口大小更新組件時,請考慮以下最佳實踐:
-
優化性能:使用
useMemo
或useCallback
記住取決於窗口大小的昂貴計算或回調功能。這可以防止不必要的重新租賃。 -
調試調整大小事件:為了防止在快速調整過程中過度更新,請考慮拒絕調整大小的活動處理程序。諸如
lodash.debounce
之類的庫對於此目的很有用。 - 條件渲染:使用窗口大小來有條件渲染不同的佈局或組件。通過將UI調整為不同的屏幕尺寸,這可以改善用戶體驗。
-
服務器端渲染兼容性:確保您的掛鉤通過使用
undefined
值初始化狀態並在訪問window
之前檢查存在的狀態,並在訪問窗口之前檢查掛鉤。 -
清理:始終在
useEffect
清理功能中清理事件聽眾,以防止內存洩漏。 - 可重複使用:設計鉤子可以在不同的組件和項目中重複使用。保持專注於單個責任(在這種情況下,跟踪窗口大小)。
- 測試:為您的自定義鉤編寫測試,以確保在各種條件下(包括不同的窗口尺寸和組件生命週期事件)正確行為。
您能提供一個如何將窗口大小跟踪鉤集成到現有的React組件中的示例?
這是如何將useWindowSize
鉤集成到現有的反應組件中的一個示例:
<code class="jsx">import React from 'react'; import useWindowSize from './useWindowSize'; // Assuming the hook is in a separate file function MyComponent() { const { width, height } = useWindowSize(); return ( <div> <h1 id="Current-Window-Size">Current Window Size</h1> <p>Width: {width}px</p> <p>Height: {height}px</p> {width > 768 ? ( <p>This is a wide screen layout</p> ) : ( <p>This is a narrow screen layout</p> )} </div> ); } export default MyComponent;</code>
在此示例中, MyComponent
使用useWindowSize
Hook來獲取當前的窗口尺寸。然後,它顯示這些維度,並使用它們根據窗口寬度有條件地呈現不同的內容。這說明瞭如何輕鬆地將鉤子集成到組件中,以根據窗口大小動態更新UI。
以上是編寫一個自定義鉤以跟踪窗口大小並更改組件時更新。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互動,可及可訪問。 1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒體綜合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityActibility.2)and tagsallowsemlessallowseamelesseamlessallowseamelesseamlesseamelesseamemelessmultimedimeDiaiaembediiaembedplugins.3)。 3)3)

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrenerabilnerabilityLikeClickLickLickLickjAckJackJacking.2)

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

使用ID選擇器在CSS中並非固有地不好,但應謹慎使用。 1)ID選擇器適用於唯一元素或JavaScript鉤子。 2)對於一般樣式,應使用類選擇器,因為它們更靈活和可維護。通過平衡ID和類的使用,可以實現更robust和efficient的CSS架構。

html5'sgoalsin2024focusonrefinement和optimization,notNewFeatures.1)增強performanceandeffipedroptimizedRendering.2)inviveAccessibilitywithRefinedwithRefinedTributesAndEllements.3)explityconcerns,尤其是withercercern.4.4)

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供應,2)語義結構,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,簡化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

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

SublimeText3漢化版
中文版,非常好用

WebStorm Mac版
好用的JavaScript開發工具

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver Mac版
視覺化網頁開發工具