问题
Minimum Reproducible Example on Github (The images don't show in this MRE, but that's ok and doesn't matter because the problem I'm wondering about has nothing to do with that)
Problem: Every time the slide index changes, the screen scrolls to the top of the page. It happens automatically.
This happens when
- incrementing the slide number by 1
- when decrementing the slide number from 3->1 or from 2->0
But does not happen when
- incrementing the slide number from slide 2 to slide 3 (slides numbered 0-3).
- decrementing the slide number by 1.
Note: When slide 3 is the active slide that means that slide 3 is the one on top, and slide 1 and 2 are the ones on the bottom.
You can see what I'm talking about in this gif below.
- Note: (The scrolling down that you see in the gif is done manually.)
Extra (In case it's useful)
I think that this may be caused by my useEffect function, which loops through each slide and assigns them to be visible or invisible and when they lay in the grid layout. When slide 4 is active, that means that slide 1 and slide 2 would be assigned to be the bottom slides first, slide 3 would then be assigned to be invisible and slide 4 would then be assigned to be the top slide.
useEffect(() => {
const slides = Array.from(document.getElementsByClassName('slide'))
const dots = Array.from(document.getElementsByClassName('dot'))
slides.forEach((slide, slideIdx) => {
if(slideIdx === index){
slide.className = "slide slide-un fade-in"
dots[slideIdx].className = "dot activeDot"
return
} else if (slideIdx === index + 1 || slideIdx === 0 && index === squares.length - 1){
slide.className = triple ? "slide slide-du fade-in" : "slide invisible"
}else if (
slideIdx === index + 2 ||
(slideIdx === 0 && index === squares.length - 2) ||
(slideIdx === 1 && index === squares.length - 1)
){
slide.className = triple ? "slide slide-twa fade-in" : "slide invisible"
}else{
slide.className = "slide invisible"
}
dots[slideIdx].className = "dot"
})
}, [index])
回答1:
What may have cause the problem was that I was manipulating the DOM directly by using document.getElementsByClassName
within my useEffect
function, and then was setting each slide to be at a certain place in the grid, or making the slide invisible. I changed my code so that an array of slides was recorded in state
const [slides, setSlides] = triple ? useState(squares.slice(0,3)) : useState([squares[0]])
I then updated the state of slides within the useEffect function, instead of manipulating their className
useEffect(() => {
if (triple){
if(index === squares.length - 1){
setSlides([squares[index]].concat(squares.slice(0,2)))
}else if(index === squares.length - 2){
setSlides(squares.slice(index, index+2).concat([squares[0]]))
}else{
setSlides(squares.slice(index, index+3))
}
}else{
setSlides([squares[index]])
}
}, [index])
来源:https://stackoverflow.com/questions/63745791/carousel-causes-screen-to-move-to-top-of-page-on-slide-change