图片 img 标签显示需要先请求到 src 资源,才可以显示。那么如何在显示前用占位图填充呢?
原理:
const [body, alter] = useState(comp)
const destory = () => alter(null)
const [style, setStyle] = useState<CSSProperties>({ display: "none" })
const visu = () => setStyle({ display: "inline" })
const [defaultImg, destory] = usePreComp(fallback)
const ref = useRef<HTMLImageElement>()
return (
<>
{defaultImg}
<img
{...props}
style={style}
ref={ref}
onError={() => ref.current.remove()}
onLoad={event => {
destory() // 销毁占位组件
visu() // 显示img
onLoad && onLoad(event)
}}
/>
</>
)
用于切换显示组件的 hook
export const usePreComp = (comp: JSX.Element): [JSX.Element, VoidFunction] => {
const [body, alter] = useState(comp)
const destory = () => alter(null)
return [body, destory]
}