React implements multi-image preview function and switching between preview images (actual example)

Preface

In React projects, displaying and previewing multiple images is a common need. This post will introduce how to use React and antdlibraries to achieve this functionality, and explore how to switch to the previous or next image in the preview modal.

background

We will demonstrate the use of the code with an example of OCR image list display. Suppose we have an OCR system that can extract text from image files. We hope to display the image list returned from the OCR system on the front end and support clicking on the image to preview it. In addition, we also hope to be able to switch to the previous or next picture in the preview modal box. The following are specific operation examples:

Operation example:

  1. First we need to import the required components and hooks:

    import React, {
          
           useEffect, useState } from 'react';
    import {
          
           Row, Col, Modal} from 'antd';
    
  2. Next, we define a Splitorcomponent that will be used to display multiple images and implement the preview function:

    const Splitor: React.FC = () => {
          
          
      const [ocrImageList, setOcrImageList] = useState<ETEST.ImageInfo[]>([]); // 图片列表的状态
      const [visible, setVisible] = useState(false); // 大图预览的可见性状态
      const [currentImage, setCurrentImage] = useState(""); // 当前点击的图片路径
    
      useEffect(() => {
          
          
        const intervalId = setInterval(updateOcrImageList, 1000 * 10); // 创建定时器,每 10 秒钟调用一次 updateOcrImageList 函数
        // 组件卸载时清除定时器
        return () => {
          
          
          clearInterval(intervalId);
        };
      }, []);
    
      const updateOcrImageList = async () => {
          
          
        try {
          
          
          const msg = await ocrList(); // 调用 ocrList 函数获取最新的图片列表
          console.log('ocrList响应数据=', msg.data);
          if (msg.isSuccess && msg.data.length > 0) {
          
          
            setOcrImageList(msg.data); // 更新图片列表状态
          }
        } catch (error) {
          
          
          console.error(error);
        }
      };
    
      const handleImageClick = (imagePath: string) => {
          
          
        setCurrentImage(imagePath); // 设置当前点击的图片路径
        setVisible(true); // 显示大图预览
      };
    
      return (
        <Row gutter={
          
          24}>
          {
          
          /* 遍历渲染图片列表 */}
          {
          
          ocrImageList.map((image) => (
            {
          
          /* 图片容器 */}
            <Col span={
          
          4} key={
          
          image.id}>
              {
          
          /* 图片元素 */}
              <div style={
          
          {
          
           border: '1px solid #ccc', borderRadius: '8px', padding: '16px', marginBottom: '20px' }}>
                <img
                  src={
          
          image.imgPath}
                  alt={
          
          image.id}
                  style={
          
          {
          
           width: '100%', objectFit: 'contain', cursor: 'pointer' }}
                  onClick={
          
          () => handleImageClick(image.imgPath)} // 点击图片时调用 handleImageClick 函数
                />
              </div>
              {
          
          /* 图片描述 */}
              <div style={
          
          {
          
           textAlign: 'center' }}>{
          
          image.content}</div> // 显示图片内容
            </Col>
          ))}
          
          {
          
          /* 大图预览弹窗 */}
          <Modal visible={
          
          visible} onCancel={
          
          () => setVisible(false)} footer={
          
          null} className="custom-modal">
            <img src={
          
          currentImage} alt="Preview" style={
          
          {
          
           height: "100%", width: "100%" }} />
          </Modal>
        </Row>
      );
    };
    

    In the above code, we use useStateto maintain multiple state variables, including ocrImageList(picture list data), visible(controlling the display and hiding of the modal box), currentImage(currently the path of the picture to be previewed).

    We use updateOcrImageListfunctions to obtain data asynchronously ocrImageList, and handleImageClickimplement the function of clicking the image to trigger the preview in the function.

    In the returned JSX, we loop through ocrImageListand use antdthe Coland Rowcomponents to display the image. After the image is clicked, handleImageClickthe function will be called to set currentImageand visiblestate, thereby displaying the preview modal box.

Expansion (preview image switching):

  1. Import new
   import Lightbox from 'react-image-lightbox';
   import 'react-image-lightbox/style.css';
  1. Switch to the previous or next picture in the preview modal box. Here are the corresponding code changes:
// ...

// 点击图片触发预览功能
const handleImageClick = (index: number) => {
    
    
    setPreviewIndex(index);
};

// 关闭预览
const handleClosePreview = () => {
    
    
    setPreviewIndex(-1);
};

// 创建预览图片路径数组
const previewImages = ocrImageList.map((image) => image.imgPath);

return (
    <Row gutter={
    
    24}>
        {
    
    /* 遍历渲染图片列表 */}
        {
    
    ocrImageList.map((image, index) => (
            <Col span={
    
    4} key={
    
    image.id}>
                {
    
    /* 图片容器 */}
                <div style={
    
    {
    
     border: '1px solid #ccc', borderRadius: '8px', padding: '16px', marginBottom: '20px' }}>
                    {
    
    /* 图片元素 */}
                    <img
                        src={
    
    image.imgPath}
                        alt={
    
    image.id}
                        style={
    
    {
    
     width: '100%', objectFit: 'contain', cursor: 'pointer' }}
                        onClick={
    
    () => handleImageClick(index)} // 点击图片时调用 handleImageClick 函数
                        />
                </div>
                {
    
    /* 图片描述 */}
                <div style={
    
    {
    
     textAlign: 'center' }}>{
    
    image.content}</div>
            </Col>
        ))}

        {
    
    /* 如果正在预览图片,渲染预览模态框 */}
        {
    
    previewIndex !== -1 && (
            <Lightbox
                // 配置预览相关属性
                mainSrc={
    
    previewImages[previewIndex]}
                nextSrc={
    
    previewImages[(previewIndex + 1) % previewImages.length]}
                prevSrc={
    
    previewImages[(previewIndex + previewImages.length - 1) % previewImages.length]}
                onCloseRequest={
    
    handleClosePreview}
                onMovePrevRequest={
    
    () => setPreviewIndex((previewIndex + previewImages.length - 1) % previewImages.length)}
                onMoveNextRequest={
    
    () => setPreviewIndex((previewIndex + 1) % previewImages.length)}
                />
        )}
    </Row>
);

// ...

In the above code, we use react-image-lightboxthe library to implement the image preview function. When the user clicks on the picture, the preview modal box will be opened, and the user can switch to the previous or next picture in the preview modal box. When closing the preview modal, the preview index will be reset to -1.

注意, the above code is just an example. You can make further styling and logic adjustments based on your needs.

Summarize

This post introduces how to use React and antd libraries to implement the multi-image preview function, and implements the extended function of switching to the previous or next image in the preview modal box. By managing state and handling user click events, we can easily implement this function. I hope this article can help you understand and apply the technical implementation method of multi-image preview.

Guess you like

Origin blog.csdn.net/Da_zhenzai/article/details/133363236