显示不同的图像反应

时间:2020-03-20 08:52:32

标签: javascript html css reactjs web

我在CSS中拥有以下类,这些类使我在一段时间后在页面上显示不同的图像:

.image-fader {
  width: 300px;
  height: 300px;
}

.image-fader img {
  position: absolute;
  top: 0px;
  left: 0px;
  animation-name: imagefade;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-duration: 8s;
}

@keyframes imagefade {
  0% {
    opacity: 1;
  }
  17% {
    opacity: 1;
  }
  25% {
    opacity: 0;
  }
  92% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.image-fader img:nth-of-type(1) {
  animation-delay: 6s;
}
.image-fader img:nth-of-type(2) {
  animation-delay: 4s;
}
.image-fader img:nth-of-type(3) {
  animation-delay: 2s;
}
.image-fader img:nth-of-type(4) {
  animation-delay: 0;
}

到目前为止,我只有显示单个图像的CSS代码:

.defaultHero,
.roomsHero {
  min-height: calc(100vh - 66px);
  background: url("./images/defaultBcg.jpeg") center/cover no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
}

我的英雄组件如下:

import React from 'react'

export default function Hero({children, hero}) {
return (
    <header className={hero}>
        {children}
    </header>
)
}

Hero.defaultProps = {
    hero: "defaultHero"
};

我在首页中这样称呼它:

import React from 'react'
import Hero from "../Components/Hero";
import Banner from "../Components/Banner";
import {Link} from 'react-router-dom';


export default function Home() {
    return (
        <Hero>
            <Banner title="Affordable Apartments" subtitle="Family
        Apartments Starting At &#8364;90 per night">
        <Link to= "/rooms" className="btn-primary">
            our apartments
        </Link>
        </Banner>
        </Hero>
    );
}

}

如何返回我的“关于”页面中的image-fader类,以返回许多图像。

1 个答案:

答案 0 :(得分:1)

使用javascript可以做到这一点:

import React from "react";
import image1 from "./img/1.png";
import image2 from "./img/2.png";
import image3 from "./img/3.png";

const imageArray = [image1, image2, image3];

const App = () => {
  const [current, setCurrent] = React.useState(0);

  React.useEffect(() => {
    const timerId = setInterval(() => {
        setCurrent(cur => (cur < imageArray.length - 1 ? cur + 1 : 0));
    }, 500);
    return () => {
        clearInterval(timerId);
    };
  }, []);

  return (
    <div>
        <img src={imageArray[current]} alt="img" />
        {current}
    </div>
  );
};
export default App;