如何在 Gatsby-plugin-image 中将图像路径作为道具传递给 Gatsby

How to pass a path of image as a prop in Gatsby in Gatsby-plugin-image

我正在尝试将图像的路径作为道具传递给组件

注意:组件和索引页都可以通过相同的路径访问图片。当我将路径作为道具传递时它不起作用

在下面的代码中,我尝试使用 GatbsyImage 和 StaticImage 标签似乎都失败了

index.js

import React from "react";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../styles/index.scss';
import Main from  '../Layouts/main';
import ImageOverlay from '../components/ImageOverlay';
import { StaticImage } from "gatsby-plugin-image"

function Home(){
  // Home page images
  return (
    <Main >
    <section className="home_page">
      <ImageOverlay path="../images/home/places/portblair.png"> </ImageOverlay>
    </section>
    </Main>
  )
}

export default Home
 

components/ImageOverlay.js

import React from 'react';
import { GatsbyImage, StaticImage } from "gatsby-plugin-image"
const ImageOverlay = ({path}) =>{
    return(

      <div>
          <GatsbyImage image={path}></GatsbyImage>
          <StaticImage src={path}></StaticImage>
      </div> 
  
    )
}
export default ImageOverlay;

我使用 GatsbyImage 和 StaticImage 以防万一检查

提前感谢您的帮助

你不能在 StaticImage 上使用外部 props,它是 known restriction:

Restrictions on using StaticImage

There are a few technical restrictions to the way you can pass props into StaticImage. Most importantly, you can’t use any of the parent component’s props. For more information, refer to the Gatsby Image plugin reference guide. If you find yourself wishing you could use a prop passed from a parent for the image src then it’s likely that you should be using a dynamic image.

并扩展参考指南:

// ⚠️ Doesn't work
export function Logo({ logo }) {
  // You can't use a prop passed into the parent component
  return <StaticImage src={logo}>
}

解决方案,如果要使用StaticImage,就是使用静态方法,直接附加src

import React from 'react';
import { GatsbyImage, StaticImage } from "gatsby-plugin-image"
const ImageOverlay = ({path}) =>{
    return(

      <div>
          <StaticImage src={`../images/home/places/portblair.png`}></StaticImage>
      </div> 
  
    )
}
export default ImageOverlay;

如果您想使用 GatsbyImage,您将需要查询您的图像以获取正确的数据:

import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"

function Home({ data }) {
 const image = getImage(data.blogPost.avatar)
 return (
   <section>
     <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]
         )
       }
     }
   }
 }
`

注意:当然,请根据您的需要调整代码段,但要明白这一点

如果你想使用动态图像,你必须进行 GraphQL 查询以允许 Gatsby 及其转换器解析和解析图像。您可以使用一堆可用的过滤器以及 relativePathabsolutePath 为您的图像创建特定查询,在 localhost:8000/___graphql.

测试查询