简体   繁体   English

如何在 nextjs 图像组件中显示占位符图像

[英]How to show a placeholder image in nextjs image component

I am trying to show images from the API calls.我正在尝试显示来自 API 调用的图像。 I want to show a placeholder image in case there are no images or any errors.我想显示一个占位符图像,以防没有图像或任何错误。 For that, I wrote this code,为此,我写了这段代码,

const [errorImage, setErrorImage] = useState(null);

  <Image
                            src={`${imageUrl}/${item.image}`}
                            alt="image"
                            layout="fill"
                            objectFit="contain"
                            onError={(e) => {
                              if (!errorImage) {
                                setErrorImage(true);
                                e.target.src = "/static/placeholder.jpg";
                              }
                            }}

But it's not working.但它不起作用。

Changing the state of errorImage when you set it to true will cause the components to re-render, so you don't need to set e.target.src directly.将errorImage的errorImage设置为true会导致组件重新渲染,所以不需要直接设置e.target.src

Option 1 Instead, you can do the following:选项 1相反,您可以执行以下操作:

const [errorImage, setErrorImage] = useState(null);
const errorImageUrl = "/static/placeholder.jpg";

  const url = errorImage ? errorImageUrl : `${imageUrl}/${item.image}`;
  <Image
    src={url}
    alt="image"
    layout="fill"
    objectFit="contain"
    onError={(e) => {
      if (!errorImage) {
        setErrorImage(true);
      }
    }}

Option 2 Alternatively, you can use the new placeholder prop that was added to <Image> component in NextJS 11. This will show a blurry version of the image you provide.选项 2或者,您可以使用在 NextJS 11 中添加到<Image>组件的新placeholder道具。这将显示您提供的图像的模糊版本。

  <Image
    src={url}
    alt="image"
    layout="fill"
    placeholder="/static/placeholder.jpg"
    objectFit="contain"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM