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

R. *_*sch 3 html css responsive-design reactjs gatsby-image

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

现在我正在这样做:

<Desktop>
  {heroImage && (
      <MyGatsbyImage
        img={heroImage}
      />
  )}
</Desktop>
<Mobile>
  {heroImageXS && (
      <MyGatsbyImage
        img={heroImageXS}
      />
  )}
</Mobile>
Run Code Online (Sandbox Code Playgroud)

其中<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>
Run Code Online (Sandbox Code Playgroud)

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

eps*_*n42 9

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

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

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
        }
      }
    }
  }
`
Run Code Online (Sandbox Code Playgroud)