【问题标题】:How can I change the fixed height of my Image in Gatsby for mobile?如何在 Gatsby for mobile 中更改图像的固定高度?
【发布时间】:2023-04-06 20:40:02
【问题描述】:

我目前正在通过我的 Gatsby 网站中的一组图像进行映射,其中每张图像都有一个 395 像素的固定高度和自动宽度。但是,对于 768 像素以下的屏幕尺寸,我需要能够将图像的固定高度更改为 200 像素。

我尝试使用两个单独的图像组件来执行此操作,并使用 windowSize 条件渲染它们,但这并没有真正起作用。

我怎样才能实现上述目标?下面是我的固定高度为 395px 的图像组件。

ScrollImage.tsx

const ScrollImage = ({ src, ...rest }) => {
  const data = useStaticQuery(graphql`
    query {
      images: allFile(
        filter: { internal: { mediaType: { regex: "/image/" } } }
      ) {
        edges {
          node {
            relativePath
            extension
            publicURL
            childImageSharp {
              fixed(height: 395) {
                ...GatsbyImageSharpFixed
              }
            }
          }
        }
      }
    }
  `);

  const match = useMemo(
    () => data.images.edges.find(({ node }) => src === node.relativePath),
    [data, src]
  );

  if (!match) return null;

  const { node: { childImageSharp, publicURL, extension } = {} } = match;

  if (extension === "svg" || !childImageSharp) {
    return <img src={publicURL} {...rest} />;
  }

  return (
    <Img
      fixed={childImageSharp.fixed}
      imgStyle={{ WebkitUserDrag: "none" }}
      {...rest}
    />
  );
};

export default ScrollImage;

【问题讨论】:

    标签: javascript reactjs gatsby gatsby-image


    【解决方案1】:

    您可以使用art-directing 方法在不同的断点处显示不同的图像。为此,您可以定义自己的固定或流动图像数组,以及每个图像的媒体密钥,并将其传递给gatsby-image 的固定或流动props。在图像上设置的媒体键可以是任何有效的 CSS 媒体查询。

    这是一个例子:

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

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 2015-08-05
      • 2016-08-17
      相关资源
      最近更新 更多