Gatsby-Image:移动/桌面的不同图像?

Gatsby-Image: Different images for Mobile / Desktop?

我想有条件地渲染我的 gatsby-image:我想为移动设备和桌面设备提供不同的图像。所以我需要把它们换掉。

现在我正在这样做:

<Desktop>
  {heroImage && (
      <MyGatsbyImage
        img={heroImage}
      />
  )}
</Desktop>
<Mobile>
  {heroImageXS && (
      <MyGatsbyImage
        img={heroImageXS}
      />
  )}
</Mobile>

其中 <Desktop><Mobile> 是带有媒体查询的样式组件,根据视口 display: block / display:none

但是:这是这里最有效的解决方案吗?我的解决方案总是在后台加载两个图像吗?

没有gatsby-image,我会这样做:

<picture>
   <source 
      media="(min-width: 650px)"
      srcset="images/img1.png">
   <source 
      media="(min-width: 465px)"
      srcset="images/img2.png">
   <img src="images/img-default.png" 
   alt="a cute kitten">
</picture>

...但这意味着不要在这里使用 gatsby-image - 我确实想使用它。

你指的是art direction。使用您问题中的方法可能会导致浏览器下载两个图像。

gatsby-image 支持艺术指导,并给出一个很好的例子说明如何在 the documentation 中应用它:

import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"

export default ({ data }) => {
  // Set up the array of image data and `media` keys.
  // You can have as many entries as you'd like.
  const sources = [
    data.mobileImage.childImageSharp.fluid,
    {
      ...data.desktopImage.childImageSharp.fluid,
      media: `(min-width: 768px)`,
    },
  ]

  return (
    <div>
      <h1>Hello art-directed gatsby-image</h1>
      <Img fluid={sources} />
    </div>
  )
}

export const query = graphql`
  query {
    mobileImage: file(relativePath: { eq: "blog/avatars/kyle-mathews.jpeg" }) {
      childImageSharp {
        fluid(maxWidth: 1000, quality: 100) {
          ...GatsbyImageSharpFluid
        }
      }
    }
    desktopImage: file(
      relativePath: { eq: "blog/avatars/kyle-mathews-desktop.jpeg" }
    ) {
      childImageSharp {
        fluid(maxWidth: 2000, quality: 100) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
`