首页 > 解决方案 > 带有反应的图像滑块

问题描述

我正在尝试添加带有反应的图像滑块,但在单击应更新数组中图像的按钮时无法弄清楚如何更新图像。


import Volleyball from '../../assets/images/volleyball.jpg'
import Gaming from '../../assets/images/gaming.jpg'
import Coding from '../../assets/images/coding.jpg'

const ImageGallary = () => {

  let imgArray = [Volleyball, Gaming, Coding];
  const [images, setImages] = useState([...imgArray])


  const prevImage = () => {

  }

return (

 <div className={classes.gallary}>
     <div className={classes.direction}>
         <button className={classes.leftArrow} onClick={prevImage}>Left</button>
         <button className={classes.rightArrow} >Right</button>
     </div>
     <div className={classes.images}>
        {images.map((a, i) => {
            return <img className={classes.image} src={a} alt="" key={i} />
         })}
     </div>

 </div>

)

标签: reactjs

解决方案


只是更改图像的一种简单方法,仅更新索引和显示,

import Volleyball from '../../assets/images/volleyball.jpg'
    import Gaming from '../../assets/images/gaming.jpg'
    import Coding from '../../assets/images/coding.jpg'

    const ImageGallary = () => {

      let imgArray = [Volleyball, Gaming, Coding];
     this.state={
    images:[...],
    currentShow:0
    }

      const prevImage = (conditon) => {
    const {images,currentShow}=this.state
       if(conditon){
    if(currentShow >= images.length){
    this.setState({currentShow:0})
    }esle{
    this.setState({currentShow:currentShow+1})
    }
       }else{
    if(currentShow < 0){
    this.setState({currentShow:images.length})
    }esle{
    this.setState({currentShow:currentShow-1})
    }
        }
      }

    return (

     <div className={classes.gallary}>
         <div className={classes.direction}>
             <button className={classes.leftArrow} onClick={()=>this.prevImage(false)}>Left</button>
             <button className={classes.rightArrow} onClick={()=>this.prevImage(true)} >Right</button>
         </div>
         <div className={classes.images}>
          <img className={classes.image} src={images[currentShow]} alt="" key={currentShow} />
         </div>

     </div>

    )

推荐阅读