H5 实现图片可预览放大等操作对库 react-photo-view 的封装和使用

例如,Taro 实现的 H5,Taro对外的提供的预览图片没有放大功能,需要自己重新封装

封装 PreviewImage 组件

import {
    
     View } from '@tarojs/components';
import {
    
     useMemo } from 'react';
import {
    
     PhotoProvider, PhotoSlider } from 'react-photo-view';
import 'react-photo-view/dist/react-photo-view.css';

import './index.less';

interface IProps {
    
    
  visible: boolean;
  current: number;
  urls: string[];
  onClose: () => void;
  onChange?: (arg: number) => void;
  photoClosable?: boolean;
}

const PreviewImage: React.FC<IProps> = ({
    
    
  visible,
  current,
  urls = [],
  onClose,
  onChange,
  photoClosable = false,
  ...rest
}) => {
    
    
  const urlsArr = useMemo(() => {
    
    
    if (urls && !!urls.length) {
    
    
      const _urls = urls.filter(v => v);
      return _urls.map((item, index) => ({
    
     src: item, key: index }));
    }
    return [];
  }, [urls]);

  return (
    <View className='xp-preview-image'>
      <PhotoProvider {
    
    ...rest}>
        <PhotoSlider
          images={
    
    urlsArr}
          photoClosable={
    
    photoClosable}
          visible={
    
    visible}
          onClose={
    
    onClose}
          index={
    
    current}
          onIndexChange={
    
    onChange}
        />
      </PhotoProvider>
    </View>
  );
};
export default PreviewImage;

使用

  const [visible, setVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<number>(0);
  {
    
    visible && (
    <PreviewImage
      visible={
    
    visible}
      current={
    
    current}
      urls={
    
    []}
      onClose={
    
    () => {
    
    
        setVisible(false);
      }}
      onChange={
    
    e => {
    
    
        setCurrent(e);
      }}
    />
  )}

猜你喜欢

转载自blog.csdn.net/yiguoxiaohai/article/details/126234669