最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I have an image that changes every 5 seconds in react.js? - Stack Overflow

programmeradmin0浏览0评论
import React, { useEffect, useState } from "react";

import aa from '../imgs/aa.png'
import aa2 from '../imgs/aa2.JPG'
import aa3 from '../imgs/aa3.JPG'
import aa4 from '../imgs/aa4.JPG'



import './AnimatedGalery.css'



export default function () {

    return (
        <div>
        </div>
    )
}

I have no idea how to start with this. I basically want an image (that I can resize and give css properties) that changes every 5 seconds to another one of those 4 imported images I have here.

import React, { useEffect, useState } from "react";

import aa from '../imgs/aa.png'
import aa2 from '../imgs/aa2.JPG'
import aa3 from '../imgs/aa3.JPG'
import aa4 from '../imgs/aa4.JPG'



import './AnimatedGalery.css'



export default function () {

    return (
        <div>
        </div>
    )
}

I have no idea how to start with this. I basically want an image (that I can resize and give css properties) that changes every 5 seconds to another one of those 4 imported images I have here.

Share Improve this question asked Apr 24, 2021 at 14:06 Lars LagauwLars Lagauw 1431 gold badge2 silver badges9 bronze badges 1
  • Use state and a setinterval which updates that state? – evolutionxbox Commented Apr 24, 2021 at 14:08
Add a ment  | 

3 Answers 3

Reset to default 5

The idea: put all imported images in a list. Have a state variable for the current image that should be displayed. Set an intervall that executes every 5 seconds in a useEffect that sets the new state with a randomly picked image.

const images = [aa, aa2, aa3, aa4];

export default function ImageSwapper() {
    const [currentImage, setCurrentImage] = useState(null);

    useEffect(() => {
        const intervalId = setInterval(() => {
            setCurrentImage(images[Math.floor(Math.random() * items.length)]);
        }, 5000)
        
        return () => clearInterval(intervalId);
    }, [])

    return (
        <div>
            <img src={currentImage} />
        </div>
    )
}

If you want to have a rotation of your images, then I would just save the currentIndex and display its image:

const images = [aa, aa2, aa3, aa4];

export default function ImageSwapper() {
    const [currentIndex, setCurrentIndex] = useState(0);

    useEffect(() => {
        const intervalId = setInterval(() => {
            if(currentIndex === images.length - 1) {
                setCurrentIndex(0);
            } 
            else {
                 setCurrentIndex(currentIndex + 1);
            }
        }, 5000)
        
        return () => clearInterval(intervalId);
    }, [])

    return (
        <div>
            <img src={images[currentIndex]} />
        </div>
    )
}

You can define a function to get current image, and use setInterval() to change image every five seconds, which you can define inside useEffect when the ponent renders:

const getPicture = index => {
  switch (index) {
    case 1:
      return "'../imgs/aa.png";

    case 2:
      ...
    default:
      break;
  }
};

const NUMBER_OF_PICTURES = 4;

export default function Menu() {
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setIndex(prevIndex => (index == NUMBER_OF_PICTURES ? 0 : prevIndex + 1));
    }, 5000);
    return () => {
      /* cleanup */
      clearInterval(timer);
    };
  /* on ponent render*/
  }, []);

  return (
    <>
      <img src={getPicture(index)} />
    </>
  );
}

you can add all the images name in a array like this :-

const temp =[aa,aa2,aa3,aa4]

const [counter,setCounter] = useState(0);

setInterval(function(){
 
counter === 4 ? setCounter(0) : setCounter(counter + 1);

 }, 5000);

In tag you can use it like this

<img src=`{temp[counter]}` />
发布评论

评论列表(0)

  1. 暂无评论