[英]How to add an onload without a fetch call in a function based component
consider the following component in react:在反应中考虑以下组件:
import React from "react";
import { Carousel } from "react-bootstrap";
function CarouselHome() {
return (
<>
<Carousel fade pause="hover" id="carousel" variant="">
<Carousel.Item>
<img
className="d-block w-100"
src="https://source.unsplash.com/1280x400/?bali"
alt="First slide"
/>
<Carousel.Caption>
<p>Bali, Indonesia</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="https://source.unsplash.com/1280x400/?maldives"
alt="Second slide"
/>
<Carousel.Caption>
<p>Maldives</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="https://source.unsplash.com/1280x400/?greece"
alt="Third slide"
/>
<Carousel.Caption>
<p>Greece</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</>
);
}
export default CarouselHome;
The source.unsplash.com returns an image, but it takes a second or so, thus the rest of the page loads before this component, I want to add a spinner while loading, how do I do this considering this is not even a fetch call? source.unsplash.com 返回一个图像,但它需要一秒钟左右,因此页面的 rest 在此组件之前加载,我想在加载时添加一个微调器,考虑到这甚至不是获取,我该怎么做称呼?
You can apply logic something like this你可以应用这样的逻辑
import React, {useState} from "react";
import { Carousel } from "react-bootstrap";
function CarouselHome() {
const [imageLoaded, setImageLoaded]=React.useState(false);
return (
<>
<Carousel fade pause="hover" id="carousel" variant="">
<Carousel.Item>
<img
className={`w-100 ${
imageLoaded ? 'd-block' : 'd-none'
}`}
src="https://source.unsplash.com/1280x400/?bali"
alt="First slide"
onLoad={()=> setImageLoaded(true)}}
/>
{!imageLoaded && (
<div className="smooth-preloader">
</div>
)}
<Carousel.Caption>
<p>Bali, Indonesia</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</>
);
}
export default CarouselHome;
i declared state variable with the name imageLoaded and changing this state on onLoad function of img and also changing the className based on state change i declared state variable with the name imageLoaded and changing this state on onLoad function of img and also changing the className based on state change
You can achieve that with this structure.您可以通过这种结构实现这一点。 Create
<Image/>
and <Loader/>
component.创建
<Image/>
和<Loader/>
组件。
const Image = ({item}) => {
const [imageLoaded, setImageLoaded] = useState(false);
const handleImageLoad = () => {
setImageLoaded(true);
};
return (
<div>
{!imageLoaded && <Loader />}
<img src={item.src} alt={item.alt} onLoad={handleImageLoad} />
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.