有没有办法找出图像资源是否加载失败?
Is there a way in react to find out if an image resource fails to load?
我有一个图像列表,我正在循环浏览这些图像并将它们显示在我的组件中,但我遇到了一个问题,考虑到其中一些图像由于服务器故障而无法加载,所以我的问题是如何才能我为这些图像提供了后备。
例如:
imageResourses.map(src => src ? <img src={src} /> : <FallbackImageComponent />)
我的挑战是,如果 src
属性 存在,我会显示实际图像,由于 server
失败,它可能导致 none 期望输出。
如果加载图像出现问题,我该如何显示我的 FallbackImageComponent
?
您可以创建一个可重复使用的 Image
组件,该组件将在图像未解析时呈现后备图像。
下面是 Image
组件的示例代码:
class Image extends React.Component {
state = {
hasError: false
};
handleError = (e) => {
this.setState({
hasError: true
});
};
render() {
if (this.state.hasError) {
return "Error Fallback Image";
}
return <img {...this.props} onError={this.handleError} />;
}
}
用法:
<Image src="..." />
查看此处的工作:https://codesandbox.io/s/heuristic-snow-5295o?file=/src/App.js:348-660
Note:
可能还有其他解决方案。如果我偶然发现它们,我会更新答案。
我有一个图像列表,我正在循环浏览这些图像并将它们显示在我的组件中,但我遇到了一个问题,考虑到其中一些图像由于服务器故障而无法加载,所以我的问题是如何才能我为这些图像提供了后备。
例如:
imageResourses.map(src => src ? <img src={src} /> : <FallbackImageComponent />)
我的挑战是,如果 src
属性 存在,我会显示实际图像,由于 server
失败,它可能导致 none 期望输出。
如果加载图像出现问题,我该如何显示我的 FallbackImageComponent
?
您可以创建一个可重复使用的 Image
组件,该组件将在图像未解析时呈现后备图像。
下面是 Image
组件的示例代码:
class Image extends React.Component {
state = {
hasError: false
};
handleError = (e) => {
this.setState({
hasError: true
});
};
render() {
if (this.state.hasError) {
return "Error Fallback Image";
}
return <img {...this.props} onError={this.handleError} />;
}
}
用法:
<Image src="..." />
查看此处的工作:https://codesandbox.io/s/heuristic-snow-5295o?file=/src/App.js:348-660
Note:
可能还有其他解决方案。如果我偶然发现它们,我会更新答案。