来自数组的 Gatsby 静态图像

问题描述

我正在尝试使用 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]
          )
        }
      }
    }
  }
`

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...