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

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

问题描述

我正在考虑将 Gatsby-Image 用于我的下一个项目,并且一直在尝试使用它.

我让它在我的测试项目中工作,但后来我想出了一个用例,我想使用来自 Gatsby 的很像常规 <img src"image.png">标签.因此,我的问题是如何使 Gatsby 组件可重用?

从react"导入 React从gatsby"导入 { StaticQuery, graphql }从盖茨比图像"导入 Img函数渲染图像({文件}){控制台日志({文件})return <Img fluid={file.childImageSharp.fluid}/>}//无状态图像组件,我猜它会接收 src 值作为道具?//返回带有查询属性和渲染属性的 StaticQuery 组件.Query prop有graphql查询来接收图像,render prop返回一个renderImage函数,作为回报,返回一个带有设置属性的Img组件från Gatsby.const 图像 = () =>(<静态查询查询={graphql`询问 {文件(相对路径:{ eq:gatsby-astronaut.png"}){childImageSharp {流体(最大宽度:300){... GatsbyImageSharpFluid}}}}`}//渲染={数据=><Img流体={data.placeholderImage.childImageSharp.fluid}/>}渲染={渲染图像}/>)导出默认图像

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

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

希望我已经说清楚了.如果您有任何问题,请提问.

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

先谢谢了,埃里克

解决方案

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

最终代码:

从'react'导入React;从'gatsby'导入{StaticQuery,graphql};从 'gatsby-image' 导入 Img;//注意:您可以将图像"更改为您喜欢的任何内容.const 图像 = 道具 =>(<静态查询查询={graphql`询问 {图像:所有文件{边{节点{相对路径名称childImageSharp {流体(最大宽度:600){... GatsbyImageSharpFluid}}}}}}`}渲染={数据=>{const image = data.images.edges.find(n => {返回 n.node.relativePath.includes(props.filename);});如果(!图像){返回空;}//const imageSizes = image.node.childImageSharp.sizes;尺寸={图像尺寸}return <Img alt={props.alt} fluid={image.node.childImageSharp.fluid}/>;}}/>);导出默认图像;

使用图片:

从'../components/Image'导入图片;<div style={{ maxWidth: `300px` }}><Image alt="太空中的盖茨比" filename="gatsby-astronaut.png"/>

说明

因为 StaticQuery 在其模板字面量中不支持字符串插值,所以我们无法真正向它传递任何道具.相反,我们将尝试在 StaticQuery 的 Render 部分中处理对 props 的检查.

注意事项

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

更新:如果您有很多图片,捆绑包的大小可能会变得非常大,因为此解决方案会扫描所有图片.

进一步定制

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

替代方案

也就是说,还有另一种方法可以解决这个问题,但需要做更多的工作/代码.

来源

  • 我修改了这篇文章中的代码.(请注意,该文章使用了已弃用的代码.)

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

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

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 ?

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.

This is an example: https://codesandbox.io/s/py5n24wk27

Thanks beforehand, Erik

解决方案

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

The final code:

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;

Using the image:

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

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.

Caveats

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.

Further customization

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

Alternatives

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

Sources

  • I modified the code from this article. (Please note that the article was using deprecated code.)

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

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