【问题标题】:How to check if image is not vallid in react?如何检查图像是否在反应中无效?
【发布时间】:2021-12-11 02:21:29
【问题描述】:

我正在尝试为 React 应用程序创建某种媒体库,但问题是有时用户可能会上传一些损坏的图片,我需要在显示之前以某种方式检查图像是否可以读取并且没有损坏。 我知道<image/> 标签上有属性 onerror,如果第一个图像不起作用,您会在其中显示其他图像。

 <img src={url} style={style} onError={this.hideImg}/> 

但问题是我使用带有图像背景的 div,所以它对我不起作用,而且我还需要显示一些文件已损坏的通知消息。 有谁知道在反应中显示文件之前是否有一些方法可以检查文件是否有效?

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    您可以在内存中(即不在页面上)创建图像,然后等待加载或出错。例如:

    const Example = ({ url }) => {
      const [status, setStatus] = useState('loading');
      useEffect(() => {
        const img = new Image();
        img.onload = () => {
          setStatus('success');
        }
        img.onerror = () => {
          setStatus('error');
        }
        img.src = url
        return () => {
          img.onload = null;
          img.onerror = null;
        }
      }, [])
    
      if (status === 'loading') {
        return null;
      } else if (status === 'error') {
        return <div>Error loading image</div>
      } else {
        return <div style={{ backgroundImage: `url(${url})`}} />
      }
    }
    

    【讨论】:

    • 非常感谢您的回答
    猜你喜欢
    • 2019-02-11
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多