gatsby - 如何在 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 只是为了检查
我在这里先向您的帮助表示感谢
解决方案
你不能使用 external props
on StaticImage
,这是一个已知的限制:
使用限制
StaticImage
将 props 传递到
StaticImage
. 最重要的是,您不能使用任何父组件的道具。有关更多信息,请参阅Gatsby Image 插件参考指南。如果您发现自己希望可以使用从父级传递的道具作为图像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 及其转换器解析和解析图像。您可以使用一堆可用的过滤器来为您的图像创建一个特定的查询,并使用relativePath
和absolutePath
测试查询localhost:8000/___graphql
。
推荐阅读
- php - 尝试为 laravel 安装 vanilo 电子商务时,yarn install 抛出错误
- javascript - 如何在 HTML 中修复此错误(未显示错误)
- javascript - 表达 res.redirect 导致“Uncaught SyntaxError: Unexpected token <”
- c++ - 在函数中使用非静态值作为默认参数
- android - 如何通过音频焦点处理使 YouTube 视频静音并且不中断音乐播放?
- java - Rabbitmq java客户端消费者handleDelivery方法没有被调用
- django - 如何更改应用程序模型显示在 Django 管理界面下
- sql - 窗口函数和通过复杂的数据操作计算平均值
- c++ - 在 list merge() 中如何调用没有 '()' 比较函数?
- python-3.x - 有没有办法在 python 3.7.1 中从用户 input() 创建一个 dict 对象?