如何根据PageQuery的结果获取盖茨比图片? [英] How to get Gatsby Images based on results of PageQuery?
问题描述
我想做类似以下的事情,以便可以动态获取盖茨比图像:
I'd like to do something like the following so I can get Gatsby Images dynamically:
const image = 'gastby-astronaut.png';
export const imageQuery = graphql`
{ allImageSharp (
filter: {
fluid: {
originalName: {
regex: "/${image}/"
}
}
}
){
edges {
node {
fluid {
originalName
}
}
}
}
}
`;
但是,我无法弄清楚如何将该查询连接到将获得"gatsby-astronaut.png"的初始查询,或者如何通过带有的子组件执行此查询.尝试此操作时出现此错误:
However, I can't figure out how to connect this query to an initial query that would get the 'gatsby-astronaut.png', or perform this query from a subcomponent with a . I get this error when I try this:
Error: BabelPluginRemoveGraphQL: String interpolations are not allowed
in graphql fragments. Included fragments should be referenced as
`...MyModule_foo`.
关于动态返回Gatsby图片的正确方法的任何建议吗?
Any suggestions on the proper way to return Gatsby Images dynamically?
推荐答案
是的,Gatsby通过静态分析从您的页面提取GraphQL查询:它们将文件作为文本加载,解析并提取查询,所有操作均在实际操作之前进行.文件被执行.这意味着您不具备典型的标记模板文字功能.
Ah, yeah Gatsby extracts GraphQL queries from your pages through static analysis: they load the file as text, parse it, and extract the query, all before the actual file gets executed. This means that your typical tagged-template literal functionality isn't there.
唯一的过滤方法是通过从gatsby-node.js
调用createPage
时提供的上下文. IE.如果您这样做:
The only way to filter is through context provided when createPage
is called from gatsby-node.js
. I.e. if you do this:
exports.createPages = ({ graphql, actions }) =>
graphql(`some query here`).then(result => {
actions.createPage({
path: "/output-path/",
component: path.resolve(`./src/templates/your_template.jsx`),
context: { image: result.data.yourImage },
})
})
然后您可以在页面查询中执行此操作:
Then you can do this in your page query:
query SomePage($image: String!) {
allImageSharp (
filter: {
fluid: {
originalName: {
regex: $image
}
}
}
){
edges {
node {
fluid {
originalName
}
}
}
}
}
这篇关于如何根据PageQuery的结果获取盖茨比图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!