【问题标题】:Gatsby-Image: Different images for Mobile / Desktop?Gatsby-Image:移动/桌面的不同图像?
【发布时间】:2020-06-25 07:25:28
【问题描述】:

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

现在我正在这样做:

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

其中&lt;Desktop&gt; 和&lt;Mobile&gt; 是带有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 - 我确实想使用它。

【问题讨论】:

    标签: html css reactjs responsive-design gatsby-image


    【解决方案1】:

    您所指的是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
            }
          }
        }
      }
    `
    

    【讨论】:

    • 你也可以使用GatsbyImageSharpSizes而不是GatsbyImageSharpFluid...虽然,这一切现在都过时了,因为gatsby-image包现在被弃用了gatsby-plugin-image,它有不同的语法.
    猜你喜欢
    • 2013-10-28
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    相关资源
    最近更新 更多