I'm developing a "slideshow" of text boxes that currently can be scrolled using arrow buttons. I would like the slideshow to auto scroll only until the user intervenes by clicking one of the arrow buttons.
Here's the relevant state logic in the React component (which I've defined as a function, not a class):
// Maintain a variable of the currently selected slide
const [slide, setSlide] = useState(0);
// Go to the next slide
function nextSlide() {
if (slide == companies.length - 1) {
setSlide(0);
} else {
setSlide(slide + 1)
}
}
The arrows will set the current slide using the setSlide function. The auto scroll I believe would best be handled by registering a call to nextSlide using setTimeout.
This works fine. setTimeout calls nextSlide, nextSlide causes a re-render, which then causes a new nextSlide to be registered and it goes on and on as expected. The issue is I can't figure out how to handle the "user intervention" aspect.
My first thought was to add an intervention boolean to the component state that gets set to true when the user clicks an arrow, and then having nextSlide only perform its logic if this boolean is set to false. After trying this, it seems that the nextSlide call registered in setTimeout has its own separate state instance, because the boolean is always false, even after I click an arrow.
Am I doing this improperly? is there a better way to do this?
Aucun commentaire:
Enregistrer un commentaire