如何循环图像数组并将它们呈现在 React 的组件中?

IT技术 javascript reactjs image loops
2021-05-16 16:26:24

我的react应用程序中有 5 张图像的列表,我想在无限循环中循环这些图像我基本上想为这 5 个帧设置动画,使灯条看起来像一盏不断移动的灯。

在此处输入图片说明

因此,在每个图像中移动的点看起来好像在移动。

我目前正在导入每个图像并在 react-bootstrapsImage组件中渲染它我知道我的方法可能在下面。我将如何准确地做到这一点?

我的尝试

//images
import bar1 from "../assets/bar1.png";
import bar2 from "../assets/bar2.png";
import bar3 from "../assets/bar3.png";
import bar4 from "../assets/bar4.png";
import bar5 from "../assets/bar5.png";

//my state
  state = {
    bars:[bar1,bar2,bar3,bar4,bar5]
  };

//function to cycle (this needs to run infinitely)
 cycleBars =()=> {
    let finalBar = this.state.bars0]; 
    //return this.state.bars[0];
    this.state.bars.map(e=>{
      finalBar = e;
    })
    return finalBar;
  }


//return from my component

<Image src={this.cycleBars()} />
2个回答

我将使用CSS 动画这是React 中的解决方案

 state = {
    bars:[bar1,bar2,bar3,bar4,bar5],
    activeImageIndex: 0
 };

 componentDidMount(){
   setInterval(()=>{
     let newActiveIndex = this.state.activeImageIndex===4 ? 0 : this.state.activeImageIndex+1     
     this.setState({
        activeImageIndex: newActiveIndex
     })
   }, 1000);


 }

 <Image src={this.state.bars[activeImageIndex]} />

一种更简单的方法可能是使用 CSS 来做到这一点:

.lightbox {
  border: solid 3px black;
  display: inline-flex;
  padding: 10px 20px;
  justify-content: space-between;
  width: 200px;
  position: relative;
  margin-left: 24px;
  align-items: center;
}

.light {
  border: solid 3px black;
  border-radius: 50%;
  height: 15px;
  width: 15px;
  animation: blink 5s linear infinite;
}

.light:nth-child(2) {
  animation-delay: 1s
}

.light:nth-child(3) {
  animation-delay: 2s
}

.light:nth-child(4) {
  animation-delay: 3s
}

.light:nth-child(5) {
  animation-delay: 4s
}

@keyframes blink {
  0% {
    background-color: orangered;
  }
  19% {
    background-color: orangered;
  }
  20% {
    background-color: transparent;
  }
  100% {
    background-color: transparent;
  }
}

.lightbox::before,
.lightbox::after {
  content: "";
  border: solid 1.5px black;
  width: 20px;
  height: 0;
  position: absolute;
}

.lightbox::before {
  left: -24px;
}

.lightbox::after {
  right: -24px;
}
<div class="lightbox">
  <div class="light"></div>
  <div class="light"></div>
  <div class="light"></div>
  <div class="light"></div>
  <div class="light"></div>
</div>