[英]Image change using setInterval in React/Gatsby with Graphql and Gatsby Image
我正在尝试根据 Graphql 查询的结果在 Gatsby/React 中创建一个图像更改组件。 我被卡住了,不知道在 setInterval function 里面做什么。 任何帮助表示赞赏。 谢谢
import React, { useState, useEffect } from "react";
import { graphql, useStaticQuery } from "gatsby";
import Img from "gatsby-image";
function ImgRotator() {
const imageData = useStaticQuery(graphql`
query {
allFile(filter: { extension: { regex: "/(jpg)|(jpeg)|(png)/" }, relativeDirectory: { eq: "rotator" } }) {
edges {
node {
id
childImageSharp {
fluid(maxWidth: 2880) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
}
}
`);
const allImages = imageData.allFile.edges;
const [images] = useState(allImages);
const [displayImage, setDisplayImage] = useState(imageData.allFile.edges[0].node.childImageSharp.fluid);
useEffect(() => {
const interval = setInterval(() => {
// Help! Don't know what to do here
}, 1000);
return () => clearInterval(interval);
}, [displayImage]);
return <Img fluid={displayImage} alt="" loading="eager" />;
}
export default ImgRotator;
一种可能对您有用的解决方法是:
import React, { useState, useEffect } from "react";
import { graphql, useStaticQuery } from "gatsby";
import Img from "gatsby-image";
function ImgRotator() {
const imageData = useStaticQuery(graphql`
query {
allFile(filter: { extension: { regex: "/(jpg)|(jpeg)|(png)/" }, relativeDirectory: { eq: "rotator" } }) {
edges {
node {
id
childImageSharp {
fluid(maxWidth: 2880) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
}
}
`);
const allImages = imageData.allFile.edges;
const [currentImage, setCurrentImage]=useState({});
const [currentIndex, setCurrentIndex]=useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCurrentImage(allImages[currentIndex].node.childImageSharp.fluid)
setCurrentIndex(currentIndex++)
}, 1000);
return () => clearInterval(interval);
}, [currentIndex]);
return <Img fluid={currentImage} alt="" loading="eager" />;
}
export default ImgRotator;
总而言之,您最初设置了两种状态:
const [currentImage, setCurrentImage]=useState({});
const [currentIndex, setCurrentIndex]=useState(0);
不言自明: currentImage
将存储您显示的图像,而currentIndex
将存储该图像数组中的索引。
在您的useEffect
(一旦currentIndex
更改触发)中,您定义了一个间隔,它在allImages
中查找currentIndex
并使用该索引设置currentImage
。 每秒钟 function 都会再次被触发,因此它将更新系统。
您的gatsby-image
将根据该间隔显示currentImage
:
return <Img fluid={currentImage} alt="" loading="eager" />;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.