【问题标题】:Loop through array of images with Javascript shows image placeholder as the previous/next image when at first/last index of array使用 Javascript 循环遍历图像数组时,在数组的第一个/最后一个索引处显示图像占位符作为上一个/下一个图像
【发布时间】:2023-01-29 21:19:22
【问题描述】:

//array of images
const programmingLanguages = [jsIcon, htmlIcon, cssIcon, csharpIcon];

显示下一张和上一张图像的功能。

   function incrementLanguage() {
   if (languageIndex + 1 === programmingLanguages.length) {
     setlanguageIndex(0);
     } else {
   setlanguageIndex(languageIndex + 1);
    }

    }
  function decrementLanguage() {
      if (languageIndex === 0) {
   setlanguageIndex(programmingLanguages.length - 1);
    } else {
   setlanguageIndex(languageIndex - 1);
    }

在这里我渲染我的图像问题是当我在 programmingLanguages [0] 上启动程序时它在左侧显示 img 占位符,因为它超出了数组。是否可以添加一个 if 语句来检查值是否低于 0 那么它应该从最后一个索引开始吗?

        /*<img id="languageIconSmall" src={programmingLanguages[if(languageIndex -1 < 0 set 
          langugeIndex to programmingLanguage.length? )]} alt=""> 
        </img>*/

        // this is the previous image                           
        <img id="languageIconSmall" src={programmingLanguages[languageIndex - 1]} alt=""> 
        </img> 
                 
        //this is the current image displayed     
        <img id="languageIcon" src={programmingLanguages[languageIndex]} alt=""></img>

        //this is the next image
        <img id="languageIconSmall" src={programmingLanguages[languageIndex + 1]} alt=""> 
         </img>

  

【问题讨论】:

    标签: reactjs arrays image carousel


    【解决方案1】:
    <img id="languageIconSmall" src={programmingLanguages[(languageIndex - 1 + programmingLanguages.length) % programmingLanguages.length]} alt="" />
             
    //this is the current image displayed     
    <img id="languageIcon" src={programmingLanguages[languageIndex]} alt="" />
    
    //this is the next image
    <img id="languageIconSmall" src={programmingLanguages[(languageIndex + 1) % programmingLanguages.length]} alt="" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      相关资源
      最近更新 更多