移动端图片预览,图片可缩放 (基于Taro)

510 阅读1分钟

1、Taro提供的APi

Taro.previewImage(option)

在新页面中全屏预览图片。预览的过程中用户可以进行保存图片、发送给朋友等操作。

样例:

Taro.previewImage({  
    current: '', // 当前显示图片的http链接  
    urls: [] // 需要预览的图片http链接列表  
})

Taro.previewImage预览图片时,无法缩放图片

2、使用 react-photo-view 库(github地址)

可预览、缩放图片

  1. 安装 npm install react-photo-view
  2. 封装 PreviewImage
import { View } from "@tarojs/components";
import { FC, useMemo } from "react";
import { PhotoProvider, PhotoSlider } from "react-photo-view";
import "react-photo-view/dist/react-photo-view.css";

interface PropsType {
  visible: boolean;
  current: number;
  urls: string[];
  onClose: () => void;
  onChange?: (arg: number) => void;
  closeAble?: boolean;
}
const PreviewImage: FC<PropsType> = (props) => {
  const {
    visible,
    current = 0,
    urls = [],
    onClose,
    onChange,
    ...rest
  } = props;

  const urlsArr = useMemo(() => {
    if (urls && urls.length) {
      return urls
        .filter((i) => i)
        .map((item, index) => ({ src: item, key: index }));
    }
    return [];
  }, [urls]);

  return (
    <View className="PreviewImage-root">
      <PhotoProvider {...rest}>
        <PhotoSlider
          images={urlsArr}
          visible={visible}
          onClose={onClose}
          index={current}
          onIndexChange={(...args) => {
            onChange && onChange(...args);
          }}
        ></PhotoSlider>
      </PhotoProvider>
    </View>
  );
};

export default PreviewImage;

  1. 使用封装的预览组件 (类组件)
// 属性
state = {
    visible: false, 
    urls: [],
    current: 0
}


const {  visible, current, urls } = this.state;
{/* 图片预览  */}
{visible && (
  <PreviewImage
    visible={visible}
    current={current}
    urls={urls}
    onClose={() => {
        this.setState({ visible: true });
    }}
    onChange={(e) => {
      this.setState({ current: e ?? 0 });
    }}
  ></PreviewImage>
)}

效果:

Dingtalk_20240719175046.jpg