【问题标题】:Is there a way in react to find out if an image resource fails to load?有没有办法找出图像资源是否加载失败?
【发布时间】:2020-09-01 13:48:43
【问题描述】:

我有一个正在循环的图像列表,并将在我的组件中显示它们,但我有一个问题,考虑到其中一些图像由于服务器故障而无法加载,所以我的问题是如何提供这些图像的后备。

例如:

imageResourses.map(src => src ? <img src={src} /> : <FallbackImageComponent />)

我的挑战是如果存在src 属性,我会显示实际图像,这可能会由于server 失败而导致无期望输出。

如果加载图片时出现问题,我该如何显示我的FallbackImageComponent

【问题讨论】:

    标签: javascript reactjs image load


    【解决方案1】:

    您可以创建一个可重用的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: 可能还有其他解决方案。如果我偶然发现它们,我会更新答案。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    相关资源
    最近更新 更多