如何遍历图像数组并在React组件中渲染它们? [英] How to loop over images array and render them in a component for React?

查看:505
本文介绍了如何遍历图像数组并在React组件中渲染它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的React应用程序中有5张图片的列表,我想在无限循环中循环浏览.我基本上想对这5帧进行动画处理,以使长条灯看起来像是不断移动的灯光.

I have a list of 5 images in my react app which I would like to cycle through in an infinite loop. I basically want to animate these 5 frames so that a light bar looks like a light that is constantly moving.

每张图像中移动的点看起来就像是在移动.

So the dot which shifts in each image will look as though it is moving.

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

I am currently importing each image and rendering it in react-bootstraps Image component. I know my approach is probably off below. How would I go about doing this accurately?

我的尝试

//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动画.这是反应中的解决方案:

I will have gone with CSS animation. Here is the solution in 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]} />

这篇关于如何遍历图像数组并在React组件中渲染它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆