如何减少轮播中显示的图像数量?

How do I reduce the number of images that appear on my carousel?

我有一个使用库 react-responsive-carousel 渲染一些图像的旋转木马,我想知道如何减少我的旋转木马中出现的图像数量。

在大屏幕尺寸下,我在旋转木马上渲染了 3 个图像,但是当屏幕变小时,我想渲染更少的图像。在下图中,很容易看出小屏幕时轮播是粘贴的图片。

我将我的代码放入 codesandbox.io

import React from "react";
import "./styles.css";
import { images } from "./carousel.data";
import "react-responsive-carousel/lib/styles/carousel.min.css";
import { Carousel } from "react-responsive-carousel";

export default function App() {
  const renderItems = images.map((img) => {
    return (
      <div key={img.id}>
        <div className="div-image">
          <img className="image" src={img.url} alt="" />
        </div>
        <div className="div-infos">
          <h3 className="info-title">Cases Title</h3>
          <span className="info-subtitle">Cases Subtitle</span>
        </div>
      </div>
    );
  });

  return (
    <div className="container-carousel">
      <div className="carousel-content">
        <Carousel
          centerMode
          showStatus={false}
          dynamicHeight={false}
          emulateTouch
          swipeScrollTolerance={50}
          centerSlidePercentage={30}
          showThumbs={false}
          infiniteLoop
          showIndicators
        >
          {renderItems}
        </Carousel>
      </div>
    </div>
  );
}

.container-carousel {
  display: flex;
  justify-content: center;
  align-items: center;
}

.carousel-content {
  width: 100%;
  max-width: 1440px;
}

.div-image {
  background-color: #fff;
  width: 100%;
  max-width: 416px;
  height: 280px;
}

.image {
  width: 100%;
  height: 100%;
  background-position: center center;
  background-repeat: no-repeat;
}

.div-infos {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}

.info-title {
  font-family: Alliance2;
  color: #000;
  line-height: 0.76;
  font-size: 2.5rem;
  letter-spacing: normal;
  font-style: normal;
  font-weight: normal;
  font-stretch: normal;
  margin: 24px 0 20px 0;
}

.info-subtitle {
  font-family: Alliance2;
  color: #000;
  line-height: 0.76;
  font-size: 1rem;
  letter-spacing: normal;
  font-style: normal;
  font-weight: 500;
  font-stretch: normal;
  text-transform: uppercase;
  margin-bottom: 30px;
}

.carousel .slide {
  background-color: transparent !important;
}

感谢您上传 CodeSandbox。所以我看了一下 Carousel 组件是如何工作的,它似乎用 <li class="slide" style="min-width: <SOME NUMBER>%">.

包装了 renderItems 数组中的每个项目。

要在 CSS 中显示不同数量的项目,您可以使用 media queries 执行以下操作。

/* For all other screen sizes, display 3 items */
.slide {
  min-width: 33% !important;
}

/* For screens with width < 600px, display 2 items */
@media only screen and (max-width: 600px) {
  .slide {
    min-width: 50% !important;
  }
}

使用的宽度百分比基本等同于100 / numItemsToShow,和!important is required to override the inline style from the react-responsive-carousel包。使用 !important 通常不是最佳做法,因此我建议您探索是否可以找到直接覆盖 react-responsive-carousel 包样式表的方法。