我一直在关注这个教程 https:/www.gatsbyjs.orgpackagesgatsby-image#art-directing-multiple-images 但正常人是不可能写50行代码来添加图片的。
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
}
}
}
}
`
我的问题是,你如何保持你的理智 并使用图像与gatsby?
这个例子有很多问题。
我使用的是一个通用的 Image
组件。
import React from "react"
import Img from "gatsby-image"
import { useStaticQuery, graphql } from "gatsby"
export default (props) => {
const { filename, type = 'default', alt, sizes = '(max-width: 400px) 100px, (max-width: 800px) 200px, 400px' } = props;
const images = useStaticQuery(graphql`
query ImageQuery {
data: allFile {
edges {
node {
relativePath
default: childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
square: childImageSharp {
fluid(maxWidth: 600, maxHeight: 600) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`);
const image = images.data.edges.find(n => {
return n.node.relativePath.includes(filename);
});
if (!image) {
return null;
}
return (
<Img alt={alt} fluid={{
...image.node[type].fluid,
sizes: sizes,
}} />
)
}
然后我传递文件名和alt文本(还可以选择类型和大小)。
<Image alt="Gravity does not apply to cats" type="square" filename="cat-defies-gravity.png" />
我同意这是一个变通的方法,直到我们得到类似于 查询2.0. 如果你阅读该页面,你会看到正是你的问题作为一个例子。