next.js 当我的下一个图像组件加载时,如果我有上一个图像,我如何显示加载微调器?

xsuvu9jc  于 2023-06-05  发布在  其他
关注(0)|答案(2)|浏览(113)

我试图显示一个加载微调器(或实际上任何HTML元素),而我的图像正在加载,事情是我使用这个ImageComponent显示一个图像在一个随机的电影生成器,我能够得到微调器的工作只是与第一个图像,但之后,当我得到一个新的电影的图像,以前的电影停留,直到新的图像加载。
下面是image组件的代码:

import Image from "next/image";
import { useState } from "react";

export default function ImageComponent(image: PrimaryImage) {
  const [loading, setLoading] = useState(true)

  function onImageLoad() {
    setLoading(false)
    console.log("loaded")
  }

  return (
    <div className="relative h-full m-auto">
      <div style={{ display: loading ? "block" : "none" }}>
        Loading Spinner goes here
      </div>
      <Image className="object-contain"
        src={image.url}
        alt="Image"
        fill
        onLoad={onImageLoad}
        priority
        style={{ display: loading ? "none" : "block" }}
      />
    </div>
  )
}

下面是整个页面的代码:

"use client"
import { useEffect, useRef, useState } from "react";
import { getMoviesRequest } from "./requests";
import MovieImageComponent from "./components/MovieImage";

export default function Page() {
  const moviesCache = useRef<Movie[]>([])
  const index = useRef(0)
  const [movie, setMovie] = useState<Movie>({
    titleText: { text: "" },
    primaryImage: { width: 0, height: 0, url: "/default_image.png" },
    releaseDate: { day: 0, month: 0, year: 0 }
  })

  useEffect(() => {
    refreshMoviesCache()
  }, [])

  function refreshMoviesCache() {
    // do some stuff to refresh the movies cache
  }
  function setNewMovie() {
    // do some stuff to set a new movie
  }

  return (
    <div>
      <h3>
        Movie Generator
      </h3>
      {MovieImageComponent(movie.primaryImage)}
      <div className="text-center p-3">
        <h1>{movie.titleText.text}</h1>
        <h2>{movie.releaseDate.year}</h2>
        <button onClick={setNewMovie}>
          Otra Pelicula
        </button>
      </div>
    </div>
  )
}

任何帮助将非常感谢。

klr1opcd

klr1opcd1#

使用if语句,像这样:

<div className="relative h-full m-auto">
    {loading ?
       <div>
         Loading Spinner goes here
       </div>
     :
       <Image className="object-contain"
         src={image.url}
         alt="Image"
         fill
         onLoad={onImageLoad}
         priority
       />
    }
</div>

每次发送新电影请求时,都需要更改loading状态。

f8rj6qna

f8rj6qna2#

你可以有一个默认图像的状态

const [imageUrl,setImageUrl]=useState(yourDefaultImageUrl)

当图片加载时,你有onImageLoad,你在这里设置最终的url:

function onImageLoad() {
    setLoading(false)
    setImageUrl(image.url)
    console.log("loaded")
  }

作为src使用imageUrl

<Image className="object-contain"
        src={imageUrl}
        alt="Image"
        fill
        onLoad={onImageLoad}
        priority
        style={{ display: loading ? "none" : "block" }}
      />

相关问题