尝试映射gatsby项目中文件夹中的图像。我根据我所看到的指南设置了一个我认为可以工作的查询。我没有得到任何错误和网站加载,但图像不显示。有什么想法吗?谢谢!
gatsby-config.js:
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},查询:
const data = useStaticQuery(graphql`
query {
allFile(filter:{extension:{regex:"/social/"}}) {
edges {
node {
childImageSharp {
fixed(width: 150, height: 150) {
...GatsbyImageSharpFixed
}
}
}
}
}
}
`)返回:
<div className='socialPhotos'>
{data.allFile.edges.map(node =>
<Img
key={node.id}
title="Photo image"
alt="Photo"
fixed={node.childImageSharp.fixed}
/>
)}
</div>发布于 2020-02-10 05:59:54
graphQL查询中的过滤器可能是问题所在。您是否在浏览器中尝试了graphiQL中的查询?
因为您在gatsby-config.js中定义了images,所以我建议使用sourceInstanceName进行过滤:
const data = useStaticQuery(graphql`
query {
allFile(filter: {sourceInstanceName: {eq: "images"}}) {
edges {
node {
childImageSharp {
fixed(width: 150, height: 150) {
...GatsbyImageSharpFixed
}
}
}
}
}
}
`)将您的查询粘贴到浏览器中的GraphiQL中,并测试是否获得数据:http://localhost:8000/___graphql
编辑
这就是如何从组件内部的查询中获取一张图像
const YourComponent = (props) => {
const { data: { allFile: { edges } } } = props;
const oneImage = edges.filter(
el => el.node.childImageSharp.fixed.originalName === "yourImageFileName.png")
[0].node.childImageSharp.fixed;
// ...https://stackoverflow.com/questions/60139088
复制相似问题