我正在使用 next/image 并且我希望图像在图像路径无效时根本不渲染,例如。图像不存在。现在它显示小图标和替代名称。在这种情况下,我不想显示任何内容。那可能吗?由于它是前端,我不能使用 fs
检查,所以我不知道该怎么做
<Image
src={`/scroll-${router.locale}.svg`}
alt="scroll"
width="240px"
height="240px"
className="opacity-50"
/>
最佳答案
您可以扩展内置的next/image
并添加 onError
如果图像无法加载,则处理程序不呈现组件。
import React, { useState } from 'react';
import Image from 'next/image';
const ImageWithHideOnError = (props) => {
const [hideImage, setHideImage] = useState(false);
return (
!hideImage && (
<Image
{...props}
onError={() => {
setHideImage(true);
}}
/>
)
);
};
export default ImageWithHideOnError;
然后您可以使用该组件而不是 next/image
.<ImageWithHideOnError
src={`/scroll-${router.locale}.svg`}
alt="scroll"
width="240px"
height="240px"
className="opacity-50"
/>
关于javascript - 图片不存在时不显示下一个/图片组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69538426/