【发布时间】:2019-07-11 07:10:49
【问题描述】:
我知道这个问题听起来有点复杂,但事实并非如此。
我尽量用简单的方式解释一下:
- 我正在为我的 Gatsby 网站的主页制作博客文章列表。
列表由“框”组成,链接到帖子的每个框都有一个背景图像。
我将此背景图像传递给样式组件,它从我插入主 元素中的 prop 值获取图像(您将找到示例下)。
它工作正常,直到我尝试使用 src 下本地文件夹中的图像(而不是使用我简单放在 frontmatter 上的在线链接)。
这是我过去所做的工作:
我把图片的url放在markdown文件的frontmatter上:
---
slug: "/post/my-post"
[...]
imghero: "https:/path/to/image-online.jpg"
---
然后用graphql查询:
const LISTING_QUERY = graphql`
query BlogPostListing {
allMarkdownRemark(limit: 10, sort: {
order: DESC,
fields: [frontmatter___date]
}) {
edges {
node {
excerpt
frontmatter {
title
slug
date(formatString: "MMMM DD, YYYY")
imghero
}
}
}
}
}
`
之后我将 {node.frontmatter.imghero} 插入到主 div 的一个道具上:
const Listing = () => (
<StaticQuery
query={LISTING_QUERY}
render={({allMarkdownRemark}) => (
allMarkdownRemark.edges.map(({node}) => (
<Article img_background={node.frontmatter.imghero} key={node.frontmatter.slug}>
[... etc ...]
</Article>
))
)}
/>
)
export default Listing
最后我在 styled-component 中调用了 img_background 属性:
const Article = styled.article`
background-image: url(${props => props.img_background};);
[... etc ...]
`
此方法有效。
现在我想从我的“图像”文件夹中获取图像,而不是从随机 url。
- 我安装了 gatsby-remark-images
- 在 gatsby-config.js 上设置它,并将一些图像的路径放在 frontmatter 上。
- 使用http://localhost:8000/___graphql 测试所有内容(并且有效)
-
通过graphql插入附加查询:
[...] frontmatter { date(formatString: "DD MMMM, YYYY") title imghero hero { childImageSharp{ fluid(maxWidth: 630) { ...GatsbyImageSharpFluid } } } [...] -
我用新路径修改了组件上的节点:
<Article img_background={node.frontmatter.hero.childImageSharp.fluid} [...]> [...] </Article> Gatsby Develop 编译正常。
但是我的主页完全是白色的。
浏览器控制台显示 node.frontmatter.hero 为“null”。
我不知道还能做什么。
感谢您的帮助。
【问题讨论】:
标签: graphql markdown gatsby styled-components yaml-front-matter