如何检查图像在反应中是否无效?

How to check if image is not vallid in react?

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

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

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

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

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})`}} />
  }
}