当我动态更改图像时,图像加载缓慢

时间:2020-07-08 20:52:17

标签: javascript html css reactjs

所以我的目标是制作一种幻灯片放映的东西,其中有一张图片(div的背景图片)。在此图像上,有四列矩形(不透明度为0.3,背景为黑色)。我有四张照片(它们不是这些div的背景而已),每个div(矩形)对应一张照片。当我将鼠标悬停在一个div(矩形)上时,背景图像应发生变化(对应于该矩形)。 enter image description here 所以我这样做了:

import React from "react";
import "./carousel.css";
import One from "./one.jpg";
import Two from "./two.jpg";
import Three from "./three.jpg";
import Four from "./four.jpg";

class Carousel extends React.Component {
  constructor() {
    super();
    this.state = { active: 1 };
  }

  changebackground = (i) => {
    this.setState({ active: i });
  };
  render() {
    const imageList = [One, Two, Three, Four];
    let style = {
      display: "grid",
      gridColumnGap: "2px",
      gridTemplateColumns: "auto auto auto auto",
      position: "relative",
      height: "100vh",
      width: "100%",
      backgroundImage: `url(${imageList[this.state.active]})`,
      backgroundRepeat: "no-repeat",
      backgroundSize: "cover",
      transition: "0.2s",
    };
    return (
      <div className="Carousel-container" style={style}>
        <div
          className="slide one"
          onMouseOver={() => this.changebackground(0)}
        ></div>
        <div
          className="slide two"
          onMouseOver={() => this.changebackground(1)}
        ></div>
        <div
          className="slide three"
          onMouseOver={() => this.changebackground(2)}
        ></div>
        <div
          className="slide four"
          onMouseOver={() => this.changebackground(3)}
        ></div>
      </div>
    );
  }
}

export default Carousel;

它工作正常,除了我的图像需要时间来加载和破坏我想要的整个动画效果。是否有某种方式可以对其进行预加载,因此不会每次都加载。

0 个答案:

没有答案