(相關資料圖)
本教程操作環境:Windows10系統、react18.0.0版、Dell G3電腦。
react怎么實現返回頂部?
知識準備:
scrollTop代表被隱藏在內容區域上方的像素數,元素未滾動時,scrollTop為0,如果元素垂直滾動了,scrollTop的值增加
目標效果:
想要實現點擊”回到頂部“按鈕以后可以回到scrollTop為0的地方,也就是頂部。
下面創建一個函數式組件ScrollDemo.js。并在里面寫入關鍵代碼,一個button,點擊時調用HandleScroll方法。button用的fixed定位
<button onClick={handleScroll} style={{ position: "fixed", top: "320px", right: "0", width: "50px", height: "50px", zIndex:"3", backgroundImage: "linear-gradient(to top, #fad0c4 0%, #fad0c4 1%, #ffd1ff 100%)", border:"0", transition:"all 1s" }}>回到頂部</button>function handleScroll(){ document.body.scrollTop = document.documentElement.scrollTop = 0; }
推薦學習:《react視頻教程》
以上就是react怎么實現返回頂部的詳細內容,更多請關注php中文網其它相關文章!
關鍵詞: React