来自数组的 Gatsby StaticImage
Gatsby StaticImage from array
我正在尝试使用 React 和 Gatsby 制作一个图像滑块,但图像没有渲染,我在控制台中得到了这个
static-image.server.tsx:51 No data found for image "undefined"
Could not find values for the following props at build time: src
这是我的代码。当我将图像源更改为 '../images/1.png'
而不是 images[sliderIndex]
时,图像将显示。
const ImageSlider = (props) => {
const [sliderIndex, setSliderIndex] = useState(0);
const images = ['../images/1.png', '../images/2.png']
useEffect(() => {
const sliderLoop = setInterval(() => {
if(sliderIndex+1 > images.length-1) {
setSliderIndex(0)
} else {
setSliderIndex(sliderIndex+1)
}
}, 5000)
return () => clearInterval(sliderLoop)
}, [sliderIndex])
console.log(sliderIndex)
return (
<>
{props.children}
<StaticImage src={images[sliderIndex]} alt=""/>
</>
)
}
<StaticImage />
仅适用于静态字符串,请参阅 this part of the docs for more info。
您必须改用 <GatsbyImage />
组件并手动查询图像数据,如 instructed here。我复制了下面的相关示例代码。
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
function BlogPost({ data }) {
const image = getImage(data.blogPost.avatar)
return (
<section>
<h2>{data.blogPost.title}</h2>
<GatsbyImage image={image} alt={data.blogPost.author} />
<p>{data.blogPost.body}</p>
</section>
)
}
export const pageQuery = graphql`
query {
blogPost(id: { eq: $Id }) {
title
body
author
avatar {
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
`
我正在尝试使用 React 和 Gatsby 制作一个图像滑块,但图像没有渲染,我在控制台中得到了这个
static-image.server.tsx:51 No data found for image "undefined"
Could not find values for the following props at build time: src
这是我的代码。当我将图像源更改为 '../images/1.png'
而不是 images[sliderIndex]
时,图像将显示。
const ImageSlider = (props) => {
const [sliderIndex, setSliderIndex] = useState(0);
const images = ['../images/1.png', '../images/2.png']
useEffect(() => {
const sliderLoop = setInterval(() => {
if(sliderIndex+1 > images.length-1) {
setSliderIndex(0)
} else {
setSliderIndex(sliderIndex+1)
}
}, 5000)
return () => clearInterval(sliderLoop)
}, [sliderIndex])
console.log(sliderIndex)
return (
<>
{props.children}
<StaticImage src={images[sliderIndex]} alt=""/>
</>
)
}
<StaticImage />
仅适用于静态字符串,请参阅 this part of the docs for more info。
您必须改用 <GatsbyImage />
组件并手动查询图像数据,如 instructed here。我复制了下面的相关示例代码。
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
function BlogPost({ data }) {
const image = getImage(data.blogPost.avatar)
return (
<section>
<h2>{data.blogPost.title}</h2>
<GatsbyImage image={image} alt={data.blogPost.author} />
<p>{data.blogPost.body}</p>
</section>
)
}
export const pageQuery = graphql`
query {
blogPost(id: { eq: $Id }) {
title
body
author
avatar {
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
`