react實(shí)現(xiàn)返回頂部的方法:1、創(chuàng)建一個(gè)函數(shù)式組件“ScrollDemo.js”;2、創(chuàng)建一個(gè)button,并通過(guò)代碼“function handleScroll(){document.body.scrollTop = document.documentElement.scrollTop = 0;}”實(shí)現(xiàn)返回頂部效果即可。
本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。
react怎么實(shí)現(xiàn)返回頂部?
知識(shí)準(zhǔn)備:
scrollTop代表被隱藏在內(nèi)容區(qū)域上方的像素?cái)?shù),元素未滾動(dòng)時(shí),scrollTop為0,如果元素垂直滾動(dòng)了,scrollTop的值增加
目標(biāo)效果:
想要實(shí)現(xiàn)點(diǎn)擊”回到頂部“按鈕以后可以回到scrollTop為0的地方,也就是頂部。
下面創(chuàng)建一個(gè)函數(shù)式組件ScrollDemo.js。并在里面寫(xiě)入關(guān)鍵代碼,一個(gè)button,點(diǎn)擊時(shí)調(diào)用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; }
登錄后復(fù)制
推薦學(xué)習(xí):《react視頻教程》