如何使用react创建自动幻灯片


import React,{useState} from 'react'
import { sliderData } from './sliderData'
import ArrowBackIosIcon from '@material-ui/icons/ArrowBackIos';
import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos';
import "./SlideShow.css"
export default function SlideShow() {
const [currentImg,setCurrentImg]=useState(0)
return (
<div >
<h3>SlideShow</h3>
<div className="slideshow" >
<div className="slider" style= 
{{backgroundImage:`url(${sliderData[currentImg].image})`}}>
<div className="left"><ArrowBackIosIcon onClick={()=>{currentImg>0 &&  
setCurrentImg(currentImg-1)}}/></div>
<div className="center"></div>
<div className="right"><ArrowForwardIosIcon onClick={()=>{ 
currentImg<sliderData.length-1 && setCurrentImg(currentImg+1)}}/></div>
</div>
</div>
</div>
)
}

我想让这个幻灯片自动移动并在悬停时暂停幻灯片。不应该在最后折叠图像

import React,{useState,useEffect} from 'react'
import { sliderData } from './sliderData'
import ArrowBackIosIcon from '@material-ui/icons/ArrowBackIos';
import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos';
import "./SlideShow.css"
export default function SlideShow() {
const [currentImg,setCurrentImg]=useState(0)
const [hovered,setHovered]=useState(false)
useEffect(() => {
if(!hovered ){
const interval=setTimeout(() => {
const newSlideIndex= currentImg>=sliderData.length-1 ?0:currentImg+1;

setCurrentImg(newSlideIndex );
}, 1000);
return(() => {

})
}
}, [currentImg])

return (

<div >
<h3>SlideShow</h3>
<div className="slideshow"  >
<div  className="slider" onMouseOver={()=>setHovered(true)}  
style= 
{{backgroundImage:`url(${sliderData[currentImg].image})`}}>
<div className="left"><ArrowBackIosIcon   onClick={()=> 
{currentImg>0 &&  setCurrentImg(currentImg-1)}}/> </div>
<div className="center"></div>
<div className="right" ><ArrowForwardIosIcon  onClick={()=>{ 
currentImg<sliderData.length-1 && 
setCurrentImg(currentImg+1)}}/></div>
</div>
</div>
</div>
)
}

悬停时暂停,但悬停后不继续滑动

相关内容

  • 没有找到相关文章