具有动态图像源的可重复使用的盖茨比图像组件 [英] Reusable Gatsby-Image Component with dynamic image sources

查看:64
本文介绍了具有动态图像源的可重复使用的盖茨比图像组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑将Gatsby-Image用于我的下一个项目,并且已经进行了一些尝试.

I’m thinking of using Gatsby-Image for my next project and has been playing around with it a little.

我可以在测试项目中使用它,但是随后我想到了一个用例,我想像常规的<img srcimage.png>标记一样使用Gatsby中的.因此,我的问题是如何使Gatsby组件可重用?

I got it to work on my test project but then I came up with a use case that I would like to use the from Gatsby much like a regular <img src"image.png"> tag. My question is therefore how I can make the Gatsby component reusable?

import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
function renderImage({ file }) {
  console.log({ file })
  return <Img fluid={file.childImageSharp.fluid} />
}

// Stateless Image component which i guess will recieve src value as a prop?
// Returns a StaticQuery component with query prop and render prop. Query prop has the graphql query to recieve the images and render prop returns a renderImage function which in return, returns a Img component från Gatsby with set attributes.
const Image = () => (
  <StaticQuery
    query={graphql`
      query {
        file(relativePath: { eq: "gatsby-astronaut.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    // render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
    render={renderImage}
  />
)
export default Image

我的最佳用例是对我在Gatsby.config文件中定义的relativePath发出动态请求,然后在每个Gatsby中组合src属性,并将其与我的资源文件中的所有图像匹配,然后显示它.你们中有人知道这种方法是否可行吗?

My optimal use case would be to make a dynamic request to my relativePath which is defined in my Gatsby.config file and then combine the src prop in each Gatsby and match it with all my images in my assets file and then display it. Do anyone of you know if this is even possible with ?

我在文档中读到,静态查询"不能接受变量-只能是页面.但是我不希望我的图像与页面相关联-我想在任何需要的地方使用此组件-像常规的img标签一样.

I read in the docs that Static Query can't take variables - only pages. But I don't want my images to be associated with a page - I want to use this component anywhere I want - like a regular img tag.

希望我已经说清楚了.请问您是否有任何疑问.

Hope I’ve made myself clear. Please ask if you have any questions.

这是一个示例: https://codesandbox.io/s/py5n24wk27

预先感谢, 埃里克

推荐答案

我也一直在寻找这个答案.希望这能回答您的问题:

I've been searching for this answer as well. Hopefully this answers your question:

import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
import Img from 'gatsby-image';

// Note: You can change "images" to whatever you'd like.

const Image = props => (
  <StaticQuery
    query={graphql`
      query {
        images: allFile {
          edges {
            node {
              relativePath
              name
              childImageSharp {
                fluid(maxWidth: 600) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        }
      }
    `}
    render={data => {
      const image = data.images.edges.find(n => {
        return n.node.relativePath.includes(props.filename);
      });
      if (!image) {
        return null;
      }

      //const imageSizes = image.node.childImageSharp.sizes; sizes={imageSizes}
      return <Img alt={props.alt} fluid={image.node.childImageSharp.fluid} />;
    }}
  />
);

export default Image;

使用图片:

import Image from '../components/Image';
<div style={{ maxWidth: `300px` }}>
    <Image alt="Gatsby in Space" filename="gatsby-astronaut.png" />
</div>

说明

由于StaticQuery在其模板文字中不支持字符串插值,因此我们无法真正将其传递给任何道具.相反,我们将尝试在StaticQuery的渲染"部分中处理道具的检查.

Explanation

Because StaticQuery doesn't support string interpolation in its template literal, we can't really pass it any props. Instead we will try and handle check for props in the StaticQuery's Render portion.

由于我们正在扫描所有图像,因此我不确定100%是否会影响编译时间.如果有,请告诉我!

I'm not 100% sure if this affects compiling time since we are scanning all images. If it does, please let me know!

更新:如果您有很多图像,则由于此解决方案可以扫描所有图像,因此捆绑包的尺寸可能会很大.

Update: If you have many images, bundle size can get quite large as this solution does scan ALL images.

如果没有传递任何道具,则可以调整代码以显示占位符图像.

You can adjust the code to show a placeholder image if no props are passed.

也就是说,您可以通过另一种方式解决此问题,但需要做更多的工作/code.

That said, there is another way you could tackle this but with a bit more work/code.

  • 我修改了本文中的代码. (请注意,本文使用的是不推荐使用的代码.)
  • I modified the code from this article. (Please note that the article was using deprecated code.)

这篇关于具有动态图像源的可重复使用的盖茨比图像组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆