【问题标题】:Gatsby StaticImage from array来自数组的 Gatsby StaticImage
【发布时间】:2021-07-07 05:33:06
【问题描述】:

我正在尝试使用 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 属性,包括 src 必须在构建应用程序的那一刻定义或计算。如果您需要更改 src,则必须选择 GatsbyImage 组件。但是,如果您制作一个滑块,将每张图片都设置为 StatisImage 并管理它们的可见性和/或定位可能是个好主意。

标签: reactjs gatsby gatsby-plugin


【解决方案1】:

&lt;StaticImage /&gt; 仅适用于静态字符串,请参阅this part of the docs for more info

您必须改用&lt;GatsbyImage /&gt; 组件并手动查询图像数据,如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]
          )
        }
      }
    }
  }
`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2021-06-13
    • 2021-09-20
    • 2021-06-20
    • 1970-01-01
    • 2021-12-09
    • 2021-06-28
    相关资源
    最近更新 更多