React使用antd的图片预览组件,点击哪个图片就预览哪个的设置

使用了官方推荐的相册模式的预览,但是点击预览之后,每次都是从图片列表的第一张开始预览,而不是点击哪张就从哪张开始预览:

所以这里我就封装了一下,对初始化预览的列表进行了逻辑处理:

当点击开始预览的时候,要找到当前图片在预览图列表中的索引,然后设置为当前预览图索引,然后等点击左右切换的时候,要改变这个索引,所以要使用onChange函数,等点击关闭按钮的时候,还要重置这个索引为点击时候的图片索引:

import './index.scss'
import { Image } from 'antd'
import { useState } from 'react'

export default function ImageItem(props: any) {
    // console.log('props', props)

    const preList = [
        'https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp',
        'https://gw.alipayobjects.com/zos/antfincdn/cV16ZqzMjW/photo-1473091540282-9b846e7965e3.webp',
        'https://gw.alipayobjects.com/zos/antfincdn/x43I27A55%26/photo-1438109491414-7198515b166b.webp',
    ]

    const [preIndex, setIndex] = useState(preList.indexOf(props.imgUrl))

    // 当点击前后切换的时候,修改当前预览图
    const handleSwitch = (current: number, prevCurrent: number) => {
        console.log('切换预览图', current, prevCurrent)
        setIndex(current)
    }

    // 关闭预览图是重置预览为当前图索引
    const handleClose = (visible: boolean) => {
        console.log('关闭预览图', visible)
        if (!visible) {
            setIndex(preList.indexOf(props.imgUrl))
        }
    }

    return (
        <div className="file">
            <Image.PreviewGroup
                items={preList}
                preview={
   
   {
                    minScale: 0.1,
                    current: preIndex,
                    onChange: handleSwitch,
                    onVisibleChange: handleClose,
                }}
            >
                <Image className="item-img" src={props.imgUrl} />
            </Image.PreviewGroup>
        </div>
    )
}

预览结果: 

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/132208694