Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

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

I have a list of 5 images in my react app which I would like to cycle through in an infinite loop .

(我的react应用程序中有5张图像的列表,我想无限循环地循环浏览 。)

I basically want to animate these 5 frames so that a light bar looks like a light that is constantly moving.

(我基本上想对这5帧进行动画处理,以使长条灯看起来像是不断移动的灯光。)

在此处输入图片说明

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

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

I am currently importing each image and rendering it in react-bootstraps Image component.

(我目前正在导入每个图像,并将其呈现在react-bootstraps Image组件中。)

I know my approach is probably off below.

(我知道我的方法可能不在下面。)

How would I go about doing this accurately?

(我将如何准确地做到这一点?)

My attempts

(我的尝试)

//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()} />
  ask by LoF10 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will have gone with CSS animation .

(我将不再使用CSS动画 。)

Here is the solution in React :

(这是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]} />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...