javascript - 如何遍历图像数组并将它们呈现在 React 的组件中?

标签 javascript reactjs image loops

我的 React 应用程序中有一个包含 5 张图像的列表,我想在无限循环 中循环显示这些图像。我基本上想为这 5 个帧制作动画,使灯条看起来像一个不断移动的灯。

enter image description here

所以每幅图像中移动的点看起来就像在移动。

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

我的尝试

//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()} />

最佳答案

我会选择 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]} />

关于javascript - 如何遍历图像数组并将它们呈现在 React 的组件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59117736/

相关文章:

reactjs - 无法读取未定义的 react 测试库的属性 'addListener'

python - 使用MSER作为关键点检测器并使用SIFT作为描述符

javascript - Angular : Directive: How to pass require form AND controller to link function

javascript - 按顺序将数组值附加到多个 div

javascript - 两个 div 同时滚动,直到一个到达底部

reactjs - React Native - 在使用 React 钩子(Hook)时减少渲染时间以优化性能

java - 文本识别库,Android、Java 代码?

html - Internet Explorer 9 到 11 中的左右空格或内嵌 svg

javascript - 尝试使用 Javascript 原型(prototype)删除多个重复代码

javascript - 我在按钮监听器的范围方面遇到问题