From 6195aa848ae1855fc0cc29253010b85c13cc20a7 Mon Sep 17 00:00:00 2001 From: afc163 Date: Thu, 9 Feb 2023 18:39:34 +0800 Subject: [PATCH] fix: fallback not working in ssr --- src/Image.tsx | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/Image.tsx b/src/Image.tsx index 5f42feac..0193ce36 100644 --- a/src/Image.tsx +++ b/src/Image.tsx @@ -52,6 +52,15 @@ interface CompoundedComponent

extends React.FC

{ type ImageStatus = 'normal' | 'error' | 'loading'; +function isImageValid(src) { + return new Promise(resolve => { + let img = document.createElement('img'); + img.onerror = () => resolve(false); + img.onload = () => resolve(true); + img.src = src; + }); +} + const ImageInternal: CompoundedComponent = ({ src: imgSrc, alt, @@ -123,9 +132,7 @@ const ImageInternal: CompoundedComponent = ({ }; const onError = (e: React.SyntheticEvent) => { - if (onImageError) { - onImageError(e); - } + onImageError?.(e); setStatus('error'); }; @@ -173,6 +180,14 @@ const ImageInternal: CompoundedComponent = ({ } }; + React.useEffect(() => { + isImageValid(src).then(isValid => { + if (!isValid) { + setStatus('error'); + } + }); + }, [src]); + // Keep order start // Resolve https://github.com/ant-design/ant-design/issues/28881 // Only need unRegister when component unMount @@ -239,7 +254,7 @@ const ImageInternal: CompoundedComponent = ({