【问题标题】:How to I resize fluid image from "gatsby-image" on my index.js page in gatsby?如何在 gatsby 的 index.js 页面上从“gatsby-image”调整流体图像的大小?
【发布时间】:2019-12-26 03:33:25
【问题描述】:

我一直在尝试调整 Gatsby 项目中 index.js 页面上的图像大小。我通过“gatsby-image”导入加载了它,我的所有代码都应该是这样,但我不知道如何调整那个 js 文件或我为样式制作的 scss 文件的大小。

我尝试更改 maxWidth 大小,但似乎所做的只是更改实际图像质量,而不是大小。我也尝试在 scss 文件中更改它,但这似乎也不起作用。

<Img fluid={props.data.imageOne.childImageSharp.fluid} />

export const fluidImage = graphql`
  fragment fluidImage on File {
   childImageSharp {
    fluid(maxWidth: 1000) {
  ...GatsbyImageSharpFluid
     }
   }
  }
`;

export const pageQuery = graphql`
 query {
  imageOne: file(relativePath: { eq: "me.jpg" }) {
  ...fluidImage
   }
 }
`

我预计图像会更小,但我目前唯一的输出是质量较低的图像,或者图像的一部分被切掉。

【问题讨论】:

  • 要将文件数据输入到 Gatsby Image,设置一个 GraphQL 查询并将其作为 props 传递到组件中,或者直接将其写入组件中。一种技术是利用 useStaticQuery 钩子。

标签: reactjs graphql gatsby


【解决方案1】:

不幸的是,您无法通过变量直接在查询中更改 maxWidth: 1000,因为 GraphQL 在构建时运行一次,然后再也不会运行。无法进行热重载。

export const fluidImage = graphql`
  fragment fluidImage on File {
   childImageSharp {
    fluid(maxWidth: 1000) {
  ...GatsbyImageSharpFluid
     }
   }
  }
`;

GraphQL 以您指定的质量向您提供图像。然后,您可以通过 CSS 调整图像大小。我记得和你有同样的问题。我将图像组件包装在一个定义了with 或min-width / max-width 的div 中。不是最优雅的解决方案,但它确实有效。

import GatsbyImage from "gatsby-image";
// ...
<ImageWrapper className="imageWrapper">
  <GatsbyImage fluid={fluid} />
</ImageWrapper>

在您的 CSS 文件中:

.imageWrapper {
   /*   min-width: 11rem; */
   /*   max-width: 20rem; */
   width: 280px;
}

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 2021-07-17
    • 2020-11-29
    • 2020-06-25
    • 1970-01-01
    • 2020-06-28
    • 2019-05-18
    • 1970-01-01
    相关资源
    最近更新 更多