下面是一个使用React类组件实现的轮播图示例,根据后端返回的数组渲染图片,并且只显示4个图,其他图片可以通过点击前后箭头进行切换显示。

import React from "react";

class Carousel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      images: [],
      currentIndex: 0
    };
  }

  componentDidMount() {
    // 假设后端返回的数组为 imageArray
    const imageArray = [
      "https://example.com/image1.jpg",
      "https://example.com/image2.jpg",
      "https://example.com/image3.jpg",
      "https://example.com/image4.jpg",
      "https://example.com/image5.jpg",
      "https://example.com/image6.jpg"
    ];
    this.setState({ images: imageArray });
  }

  handlePrev = () => {
    const { currentIndex } = this.state;
    if (currentIndex === 0) {
      this.setState({ currentIndex: this.state.images.length - 1 });
    } else {
      this.setState({ currentIndex: currentIndex - 1 });
    }
  };

  handleNext = () => {
    const { currentIndex } = this.state;
    if (currentIndex === this.state.images.length - 1) {
      this.setState({ currentIndex: 0 });
    } else {
      this.setState({ currentIndex: currentIndex + 1 });
    }
  };

  render() {
    const { images, currentIndex } = this.state;
    const visibleImages = images.slice(currentIndex, currentIndex + 4);
    return (
      <div className="carousel">
        <div className="images-container">
          {visibleImages.map((image, index) => (
            <img key={index} src={image} alt={`Image ${index + 1}`} />
          ))}
        </div>
        <button className="prev-button" onClick={this.handlePrev}>
          Previous
        </button>
        <button className="next-button" onClick={this.handleNext}>
          Next
        </button>
      </div>
    );
  }
}

export default Carousel;

在这个示例中,我们使用componentDidMount生命周期方法模拟从后端获取图片数组,并将其存储在组件的状态中。

然后,我们根据当前的currentIndex和图片数组长度来确定可见图片的范围,并使用Array.slice方法来获取这些图片。

handlePrevhandleNext方法中,我们根据当前的currentIndex来更新状态,以实现图片的切换。当currentIndex到达边界时,我们将其设置为数组的最后一个或第一个索引,从而实现循环切换。

最后,我们在渲染方法中使用map函数来遍历可见图片,并将其作为<img>元素的src属性值进行渲染。我们还添加了前后箭头按钮,并将handlePrevhandleNext方法分别绑定到它们的onClick事件上,以实现点击切换图片的功能。

请根据你的实际需求对CSS样式进行自定义,以使其符合你的项目要求

react 类组件根据后端返回的数组写一个轮播图带自定义的前后箭头只显示4个图其他图片靠左右箭头切换显示

原文地址: http://www.cveoy.top/t/topic/iTYf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录