[英]How can I change slides with useState in react?
It's probably a basic stuff, but I'm trying to figure out how can I change slides clicking on button.这可能是一个基本的东西,但我试图弄清楚如何点击按钮更改幻灯片。 I have divs with data from movies API, so I'm clicking a button and I change slides, toggling active class in it.
我有来自电影 API 的数据的 div,所以我单击一个按钮并更改幻灯片,在其中切换活动类。 I can imagine doing it in plain javascript, but I'm trying to understand how can I do it in React.
我可以想象用普通的 javascript 来做,但我试图了解如何在 React 中做到这一点。 The function looks like this:
该函数如下所示:
const [currentSlide, setCurrentSlide] = useState(0);
function changeSlide(){
if(currentSlide <= few_movies.length){
setCurrentSlide(currentSlide + 1);
}else if(currentSlide >= few_movies.length){
}
}
Quick answer YES you can make slides change using useState hook.快速回答是的,您可以使用 useState 挂钩更改幻灯片。
I suggest you hold all slides(movies) in an array or to have some indexed value for them like id, and then you can just make the math to change them based on the current slide index.我建议您将所有幻灯片(电影)保存在一个数组中,或者为它们设置一些索引值,例如 id,然后您可以根据当前幻灯片索引进行数学运算来更改它们。 and on click event should increment or decrement the index if the current slide is for example 5 and you want to see prev slide you should just set the value of the state to current - 1. And that is basically the logic.
如果当前幻灯片是例如 5,并且您想查看上一张幻灯片,则单击事件应该增加或减少索引,您应该将状态的值设置为当前 - 1。这基本上是逻辑。
For returning ( displaying the slide ) You just watch which data from API have the same id (index) as the current slide, and just display its data.返回(显示幻灯片)您只需查看来自 API 的哪些数据与当前幻灯片具有相同的 id(索引),并仅显示其数据。
Hope you could understand and I did not confuse you.希望你能理解,我没有混淆你。 Good luck, happy codding.
祝你好运,快乐编码。
instead of setting it to setCurrentslide(0)<\/code> why not just do nothing ?
而不是将其设置为
setCurrentslide(0)<\/code>为什么不什么都不做呢?
same if they are at slide index
0<\/code> then don't let them go further down than
0<\/code>
如果它们在幻灯片索引
0<\/code>处相同,那么不要让它们进一步低于
0<\/code>
currentSlide.length >= few_movies.length ? console.log('do nothing') : setCurrentSlide(oldState => oldState +1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.