簡體   English   中英

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 - 我確實想使用它。

你所指的是所謂的藝術指導 在您的問題中使用該方法可能會導致瀏覽器下載兩個圖像。

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
        }
      }
    }
  }
`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM