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

问题描述

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

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

在下面的代码中,我尝试使用 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
 

组件/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 只是为了检查

提前感谢您的帮助

解决方法

您不能在 props 上使用外部 StaticImage,它是一个 known restriction

使用 StaticImage

的限制

传递道具的方式有一些技术限制 进入StaticImage。最重要的是,您不能使用任何父级 组件的道具。有关详细信息,请参阅 Gatsby Image plugin reference guide。如果您发现自己希望可以使用 从父级为图像 src 传递的道具,那么您很可能 应该使用动态图片。

并扩展参考指南:

// ⚠️ 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 测试查询。

相关问答

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