在 NextJS 中拥有后备图像的最佳方法是什么? [英] What is the best way to have a fallback image in NextJS?

查看:50
本文介绍了在 NextJS 中拥有后备图像的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我一直在用 NextJS 开发一个项目,该项目使用 YoutubeAPI 来获取视频信息,包括缩略图 URL.

Recently, I have been working on a project in NextJS which uses the YoutubeAPI to fetch video information, including thumbnail URLs.

全分辨率图像的缩略图 URL 如下所示:https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg

The thumbnail URL for a full resolution image looks like this: https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg

但是,有时 YouTube 无法生成全分辨率图像,在这种情况下,图像不会显示在我的网页上.

However, sometimes YouTube fails to generate a full-resolution image, and in that case, the image is not displayed on my webpage.

如果带有 URL https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg 的图像不存在,我希望使用另一个 URL,例如 <代码>https://i.ytimg.com/vi/${videoId}/hqdefault.jpg

In the case that the image with the URL https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg does not exist I wish to use another URL like https://i.ytimg.com/vi/${videoId}/hqdefault.jpg

使用 next/image 处理此问题的最佳方法是什么?

What is the best way to handle this with next/image?

推荐答案

@juliomalves 已经给出了 99% 的答案,但是我想补充一下.在他的解决方案中更改 src 时出现问题,因为图像不会更新,因为它正在获取未更新的 imgSrc 值.这是我对他的回答的补充:

@juliomalves has given 99% percent of the answer, however I would like to add to it. There is a problem when changing the src in his solution, as the image would not update because it's getting the imgSrc value which is not getting updated. This is my addition to his answer:

import React, { useState } from 'react';
import Image from 'next/image';

const ImageFallback = (props) => {
    
    const { src, fallbackSrc, ...rest } = props;
    const [imgSrc, setImgSrc] = useState(false);
    const [oldSrc, setOldSrc] = useState(src);
    if (oldSrc!==src)
    {
        setImgSrc(false)
        setOldSrc(src)
    }
    return (
        <Image
            {...rest}
            src={imgSrc?fallbackSrc:src}
            onError={() => {
                setImgSrc(true);
            }}
        />
    );
};

export default ImageFallback;

现在 imgSrc 仅用作标志,并且有 src 值的跟踪,这有助于更改图像,即使您之前有一个带有后备图像的图像.

Now imgSrc is used only as a flag, and there is tracking of src value, which helps to change the image even if you had an image that had the fallback image on before.

这篇关于在 NextJS 中拥有后备图像的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆