【 react 】《 React实现图片比对效果 》

发布时间 2023-12-28 10:21:57作者: 芋白

这里使用 img-comparison-slider 组件进行实现,官网地址如下

https://img-comparison-slider.sneas.io/examples.html#always-show

实现效果

拖动中间分割线来切换展示旧图片与新图片

安装组件

## 安装组件
npm install @img-comparison-slider/react

组件应用

/* 解构组件 */
import { ImgComparisonSlider } from '@img-comparison-slider/react'
interface IProps {
    imgs: any[]
}

const Slider: React.FC<IProps> = (props) => {
    if (props.imgs.length > 0) {
        /* 使用标签 */
        return <ImgComparisonSlider
            children={
                <>
                    {/* 传值旧图片 */}
                    <img width={'100%'} slot="first" src={props.imgs[0]} alt="" />
                    {/* 传值新图片 */}
                    <img width={'100%'} slot="second" src={props.imgs[1]} alt="" />
                    {/* 设置分割线样式 */}
                    <svg slot="handle" xmlns="http://www.w3.org/2000/svg" width="100" viewBox="-8 -3 16 6">
                        <path stroke="#fff" d="M -5 -2 L -7 0 L -5 2 M -5 -2 L -5 2 M 5 -2 L 7 0 L 5 2 M 5 -2 L 5 2" strokeWidth="1" fill="#fff" vectorEffect="non-scaling-stroke"></path>
                    </svg>
                </>
            }
        />
    }
    return null
}

export default Slider;