我正在使用 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"
/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)