React Native通用组件封装(Image)

2022-12-13  本文已影响0人  G_console

图片组件封装,可以只设宽度,高度自动计算

import React from 'react';
import { Image as RNImage, ImageProps as NativeImageProps, ImageSourcePropType, ImageURISource } from 'react-native'
import { TouchableOpacity } from '@/components'

interface Props extends NativeImageProps {
  source: ImageURISource
  width?: number
  height?: number
  setHeight?: (height:number) => void
  onClick?: () => void
}

interface State {
  imageW?: number
  imageH?: number
}

//图片自适应高度
class Image extends React.PureComponent<Props, State>{
  public state:State = {
    
  };

  componentDidMount(){
    const { width, height, source, setHeight } = this.props
    if(width && height) {
      this.setState({
        imageW: width,
        imageH: height,
      })
      return;
    }
    if(width) {
      this.setState({
        imageW: width
      })
      if(source.uri){
        // 网络图片
        RNImage.getSize(source.uri,(w, h)=>{
          this.setState({
            imageH: width * h / w
          })
        })
      }else{
        // 本地资源
        const result =  RNImage.resolveAssetSource(source)
        let h = result.height
        let w = result.width
        const finalHeight = width * h / w
        this.setState({
          imageH:finalHeight
        })
        setHeight && setHeight(finalHeight)
      }  
    }
  }

  render(){
    const { imageW, imageH } = this.state
    const { width, height, onClick } = this.props
    return (
      <TouchableOpacity onPress={onClick} 
        style={[this.props.style,
          {
            width: imageW || width || 100,
            height: imageH || height || 100,
          }
        ]}
      >
        <RNImage
          style={[this.props.style,
            {
              width: imageW || width || 100,
              height: imageH || height || 100,
            }
          ]}
          source={this.props.source}
          
        />
      </TouchableOpacity>
    );
  }
}

export { Image }
上一篇下一篇

猜你喜欢

热点阅读