如何在Next.js中加载图像时显示微调器



我试图在Next.js网站上加载图像时显示微调器。我使用NextUI作为UI库。

我在网站上有一堆卡片,想在加载图像时显示一个微调器。我尝试过React钩子和三元运算符:

import Loader from '../components/Loader'
import spinner from '../public/images/spinner.svg'
const Item = ({ item }) => {
const [isLoading, setIsLoading] = useState(false);

useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
const result = await {item};   
setIsLoading(false);
};
fetchData();
}, []);

return (
<Link href={`/item/${item.id}`}>
<Card flat isHoverable isPressable css={{ mw: "400px", alignContent: 'center'}}>
{isLoading ? (
<Loader />
) : (
<Card.Image src={item.pic} alt={item.id} layout='responsive' css={{ alignContent: 'center'}} placeholder='blur' blurDataURL='/../public/images/spinner.svg'/>
)}

("Loader"是正确的,我已将UI库中的"Loading"重命名为

我还尝试过使用Next的blurDataUrl属性,但似乎也不起作用。

这对我来说很有效,当加载图像时,会显示一个循环加载的

import {useState, useEffect} from 'react';
import Image from "next/image";
import { CircularProgress } from "@mui/material";
import { styled } from "@mui/system";
export default function ServiceImage(props: any) {  
const { src, alt } = props.props;
const [isImageLoaded, setIsImageLoaded] = useState(false);
useEffect(()=> {
setIsImageLoaded(false);
}, [src, alt]);
const StyledImage = styled(Image)(({ theme }) => ({
objectFit: "cover",    
objectPosition: "50% 50%",
[theme.breakpoints.up("md")]: {
objectFit: "contain",
}
}));
return (
<>
<StyledImage src={src} alt={alt} fill onLoadingComplete={() => {
setIsImageLoaded(true);
}}
sx={{
opacity: isImageLoaded ? 1 : 0,
transitionDuration: "500ms",
transitionProperty: "opacity",
transitionTimingFunction: "ease-out",
}}
/>
<CircularProgress size={80} thickness={3} sx={{ 
position: "absolute", 
top:"50%", 
left: "50%", 
transform: "translate(-50%, -50%) !important",
opacity: !isImageLoaded ? 1 : 0,
transitionDuration: "500ms",
transitionProperty: "opacity",
transitionTimingFunction: "ease-out",
}} />
</>
);
}

相关内容

  • 没有找到相关文章

最新更新