React 图片加载失败调用onError显示默认图,不展示裂图片
import React, { useState } from 'react'
const Image = (props: any) => {
let {
defaultImg ='https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=91016227,2090420577&fm=26&gp=0.jpg',
...rest
} = props
const [isError, setIsError] = useState(true)
const imgerrorfun = (event: any) => {
// 只调用一次onError 防止默认图加载不出来导致死循环
if (isError) {
setIsError(false)
event.target.src = defaultImg
}
}
return <img onError={imgerrorfun} alt="" {...rest} />
}
export default Image
如图:
test1.png
网友评论