在開發(fā)中棒搜,經(jīng)常遇到圖片加載失敗的情況,如果圖片加載失敗活箕,顯示一個錯誤標志會嚴重影響用戶體驗度力麸。如果在判斷圖片加載失敗后顯示默認圖片就解決這個問題。
img 標簽有src屬性,用來給定圖片的地址克蚂,還有一個onError屬性表示圖片加載失敗觸發(fā)的事件屬性闺鲸,有了這個屬性就很好做圖片加載失敗的處理了。
<img src="" onError="" />
一埃叭、使用hook方式封裝組件
import React, {useState, useEffect} from 'react';
/**
* 圖片加載失敗就顯示默認圖片
* 使用hook方式
* @param {*} src 圖片路徑
* @param {*} style 圖片樣式
* @param {*} defaultImg 默認顯示的圖片路徑
*/
const MyImg = ({src, style, defaultImg}) => {
const [imgSrc, handleImageErrored] = useState(src);
// useEffect(() => {
// 組件更新
// });
return (
<img style={style}
src={imgSrc}
onError={() => handleImageErrored(defaultImg)}
/>
);
}
export default MyImg;
二摸恍、react普通封裝組件的方法:
import React from 'react';
/**
* 圖片加載失敗就顯示默認圖片
*/
class MyImg extends React.Component {
constructor(props){
super(props);
this.state = {
src: props.src
}
}
// 父組件更新后,子組件更新赤屋,這里可以優(yōu)化
componentWillReceiveProps(nextprops) {
this.setState({src: nextprops.src});
}
// 圖片加載失敗立镶,將默認值賦值給src
handleImageErrored() {
const { defaultImg } = this.props;
this.setState({
src: defaultImg
});
}
render() {
return (
<img style={this.props.style}
src={this.state.src}
onError={this.handleImageErrored}
/>
);
}
}
export default MyImg;
三、使用方式:
import MyImg from '@/component/MyImg';
...
<MyImg
src={`${BASE_URL}${photoPath}`}
defaultImg={require('...')}
/>
...