问题描述
我目前正在 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;
解决方法
您可以使用 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
}
}
}
}
`