美文网首页
React Native通用组件封装(Image)

React Native通用组件封装(Image)

作者: G_console | 来源:发表于2022-12-13 14:44 被阅读0次

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

    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 }
    

    相关文章

      网友评论

          本文标题:React Native通用组件封装(Image)

          本文链接:https://www.haomeiwen.com/subject/lwphqdtx.html