試圖實作 "到達頂部 "按鈕,但它似乎并沒有按照預期作業。我想我得到了正確的代碼和數值,但我的設定并不正確。我有以下的結構,在我的index.tsc中,我有一個Base組件,有這樣的代碼
。const Base=()=> {
const [showButton, setShowButton] = useState(false);
const handleScroll = (/span>) => {
if (window.scrollY > 300) {
setShowButton(true)。
} else {
setShowButton(false)。
}
};
useEffect(() => {
window.addEventListener('roll', handleScroll, true)。
return () =>/span> window. removeEventListener('scroll', handleScroll, true)。
});
//此函式將滾動視窗到頂部。
const scrollToTop = (/span>) => {
window.scrollTo(0, 0) 。
};
return (
<div className="antialiased text-gray-600 h-screen w-screen flex flex-col overflow-y-auto"/span>>/span>
scrollY回傳設備的高度,而不是滾動的位置。
const Index=()=>。<Base />。
試過使用document.body和使用scrollYOffset,都回傳同樣的東西
。uj5u.com熱心網友回復:
請檢查你的用戶界面中實際滾動的是什么--視窗還是組件。你已經添加了overflow-y-auto className,很可能是你的div組件在滾動。
我已經添加了一個非常基本的片段,其中視窗正在滾動,請嘗試滾動它。
。class App extends React. 組件{
componentDidMount(){
window.addEventListener("roll",()=>console. log(window.scrollY)
}
render(){
return(<div>)
{[1,2,3,4,5,6,7,8,9].map(i=>(
<div style={{height:"200px",borderBottom: "1px solid"}}>{i}</div>/span>
))}
</div>)
}
}
ReactDOM.render(
<App/>>。
document.getElementById('root'));
<script src="https://cdnjs. cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js">/span></script>
<script src="https://cdnjs.cloudflare. com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>/span>
<div id="root"/span>> </div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
如果是一個組件滾動:
const handleScroll=(e)=> {
if((e.scrollHeight-(e.scrollTop e.clientHeight))> 300){
setShowButton(true)。
}
else setShowButton(false)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/307922.html
標籤:
下一篇:如何動態地插入到一個集合中?
