|
|
|
@ -3,16 +3,19 @@ import {Image, ImageProps, View} from "@tarojs/components"; |
|
|
|
|
import shard from '@/static/img/shard.png' |
|
|
|
|
import styles from './image.module.scss' |
|
|
|
|
import Taro from "@tarojs/taro"; |
|
|
|
|
import avatar from '@/static/img/avatar.png' |
|
|
|
|
|
|
|
|
|
interface Props extends ImageProps { |
|
|
|
|
width?: number | string |
|
|
|
|
height?: number | string |
|
|
|
|
fallback?: string |
|
|
|
|
errorType?: "acquiesce" | 'avatar' |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
const Img: FC<Props> = ({src, mode = 'aspectFill', width, height, fallback = shard, ...props}) => { |
|
|
|
|
const [isError, setIsError] = useState(false) |
|
|
|
|
const [loading, setLoading] = useState(true) |
|
|
|
|
const [errorUrl, setErrorUrl] = useState(fallback) |
|
|
|
|
|
|
|
|
|
const imgAnimation = Taro.createAnimation({duration: 0}).opacity(0).step() |
|
|
|
|
const [animationData, setAnimationData] = useState<TaroGeneral.IAnyObject>(imgAnimation.export()) |
|
|
|
@ -22,6 +25,18 @@ const Img: FC<Props> = ({src, mode = 'aspectFill', width, height, fallback = sha |
|
|
|
|
setLoading(!!src) |
|
|
|
|
}, [src]) |
|
|
|
|
|
|
|
|
|
useEffect(() => { |
|
|
|
|
switch (props.errorType) { |
|
|
|
|
case undefined: |
|
|
|
|
case "acquiesce": |
|
|
|
|
setErrorUrl(fallback) |
|
|
|
|
break |
|
|
|
|
case "avatar": |
|
|
|
|
setErrorUrl(avatar) |
|
|
|
|
break |
|
|
|
|
} |
|
|
|
|
}, [props.errorType]) |
|
|
|
|
|
|
|
|
|
// 图片加载失败
|
|
|
|
|
function onErrorHandler() { |
|
|
|
|
setLoading(false) |
|
|
|
@ -40,7 +55,7 @@ const Img: FC<Props> = ({src, mode = 'aspectFill', width, height, fallback = sha |
|
|
|
|
style={{ |
|
|
|
|
width: `${width}rpx`, |
|
|
|
|
height: `${height}rpx`, |
|
|
|
|
backgroundColor: '#F8F8F8' |
|
|
|
|
backgroundColor: (isError || !loading) ? 'transparent' : '#F8F8F8' |
|
|
|
|
}} |
|
|
|
|
className={`${props?.className} ${styles.imgBox}`}> |
|
|
|
|
{!isError && |
|
|
|
@ -51,8 +66,12 @@ const Img: FC<Props> = ({src, mode = 'aspectFill', width, height, fallback = sha |
|
|
|
|
mode={mode} |
|
|
|
|
lazyLoad |
|
|
|
|
fadeIn |
|
|
|
|
defaultSource={fallback} |
|
|
|
|
style={{width: width ? `${width}rpx` : "100%", height: height ? `${height}rpx` : "100%"}} |
|
|
|
|
defaultSource={errorUrl} |
|
|
|
|
style={{ |
|
|
|
|
width: width ? `${width}rpx` : "100%", |
|
|
|
|
height: height ? `${height}rpx` : "100%", |
|
|
|
|
verticalAlign: 'middle' |
|
|
|
|
}} |
|
|
|
|
onError={onErrorHandler} |
|
|
|
|
onLoad={onLoadHandler}/> |
|
|
|
|
</View> |
|
|
|
@ -62,7 +81,7 @@ const Img: FC<Props> = ({src, mode = 'aspectFill', width, height, fallback = sha |
|
|
|
|
<Image |
|
|
|
|
className={styles.imgError} |
|
|
|
|
mode='aspectFill' |
|
|
|
|
src={fallback} |
|
|
|
|
src={errorUrl} |
|
|
|
|
lazyLoad |
|
|
|
|
fadeIn |
|
|
|
|
style={{ |
|
|
|
|