我有以下文件夹结构
/images
/images/pic1.jpg
/images/pic2.jpg
使用以下GraphQL查询时。
query MyQuery1 {
file(sourceInstanceName: {eq: "images"}, name: {eq: "pic1"}) {
name
publicURL
}
}
可以使用<img src={data.file.publicUrl} alt="" />
之类的东西来访问结果。到目前为止,一切都很好。
但是现在我想通过一个查询从该文件夹中检索多个图像。因此,我提出了以下建议:
query {
allFile(
filter: {
sourceInstanceName: { eq: "images" }
name: { in: ["pic1", "pic2"] }
}
) {
nodes {
name
publicURL
}
}
}
太好了!但是,现在如何不使用map
或遍历结果而访问那些图像之一?
我正在寻找类似的东西,但那当然不起作用:
<img src={data.file.publicUrl name.eq="pic1"} alt="pic1"/>
Nor不会这样:
<img src={data.allFile.nodes.0.publicUrl} alt="pic1" />
我想使用gatsby-image
来优化图像并调整其大小。这就是为什么我选择GraphQL方法而不是直接导入的原因。我走错了路吗?
答案 0 :(得分:1)
我自己弄清楚了。我不知道一个人可以将链接在一起。这对我有用。
query {
imageOne: file(sourceInstanceName: {eq: "images"}, relativePath: {eq: "pic1.jpg"}) {
id
childImageSharp {
fixed(width: 30) {
base64
tracedSVG
aspectRatio
width
height
src
srcSet
srcWebp
srcSetWebp
originalName
}
}
}
imageTwo: file(sourceInstanceName: {eq: "images"}, relativePath: {eq: "pic2.jpg"}) {
id
childImageSharp {
fixed(width: 30) {
base64
tracedSVG
aspectRatio
width
height
src
srcSet
srcWebp
srcSetWebp
originalName
}
}
}
}
然后像这样访问它:
<Img fixed={data.imageOne.childImageSharp.fixed} alt="" />
和
<Img fixed={data.imageTwo.childImageSharp.fixed} alt="" />
P.S:这是gatsby-config.js
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`, <<== gets filtered by sourceInstanceName: ..
path: `${__dirname}/src/images/`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
答案 1 :(得分:1)
OP回答了他们自己的问题,但这是另一种方法:使用Array.prototype.filter
const Index = (props) => {
const { data: { allFile: { edges } } } = props;
const heroImage = edges.filter
(el => el.node.childImageSharp.fluid.originalName === "heroImage.png")
[0].node.childImageSharp.fluid;
// ...
}
export const query = graphql`
{
allFile(filter: {
extension: {eq: "png"},
sourceInstanceName: {eq: "images"}},
sort: {fields: [childImageSharp___fluid___originalName], order: ASC})
{
edges {
node {
childImageSharp {
fluid(maxWidth: 300, quality: 50) {
originalName
...GatsbyImageSharpFluid
}
}
}
}
}
}
`;