我正在考虑在我的下一个项目中使用 Gatsby-Image,并且已经尝试了一些。
我让它在我的测试项目上工作,但后来我想出了一个用例,我想像使用常规 <img src”image.png”>
一样使用 Gatsby 的
import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
function renderImage({ file }) {
console.log({ file })
return <Img fluid={file.childImageSharp.fluid} />
}
// Stateless Image component which I guess will
// receive the 'src' value as a property?
//
// It returns a StaticQuery component with a query property
// and render property. The query property has the GraphQL
// query to receive the images and render prop returns a
// renderImage function which in return, returns an Img
// component from Gatsby with set attributes.
const Image = () => (
<StaticQuery
query={graphql`
query {
file(relativePath: { eq: "gatsby-astronaut.png" }) {
childImageSharp {
fluid(maxWidth: 300) {
...GatsbyImageSharpFluid
}
}
}
}
`}
// render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
render={renderImage}
/>
)
export default Image
我的最佳用例是向我的 Gatsby.config 文件 中定义的 relativePath 发出动态请求,然后在每个 Gatsby 中组合 src 属性 < Image/> 并将其与我的 Assets 文件中的所有图像匹配,然后显示它。这甚至可以用
我在文档中读到,StaticQuery 不能使用变量 - 只能使用页面。但我不希望我的图像与页面相关联 - 我想在任何我想要的地方使用这个组件 - 就像一个普通的 img 标签。
最佳答案
这可能会回答您的问题:
最终代码:
import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
import Img from 'gatsby-image';
// Note: You can change "images" to whatever you'd like.
const Image = props => (
<StaticQuery
query={graphql`
query {
images: allFile {
edges {
node {
relativePath
name
childImageSharp {
fluid(maxWidth: 600) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`}
render={data => {
const image = data.images.edges.find(n => {
return n.node.relativePath.includes(props.filename);
});
if (!image) {
return null;
}
//const imageSizes = image.node.childImageSharp.sizes; sizes={imageSizes}
return <Img alt={props.alt} fluid={image.node.childImageSharp.fluid} />;
}}
/>
);
export default Image;
使用图像:
import Image from '../components/Image';
<div style={{ maxWidth: `300px` }}>
<Image alt="Gatsby in Space" filename="gatsby-astronaut.png" />
</div>
解释
因为 StaticQuery 不支持在其模板字面量中进行字符串插值,我们无法真正传递给它任何 props。相反,我们将尝试处理 StaticQuery 的渲染部分中的 Prop 检查。
注意事项
我不能 100% 确定这是否会影响编译时间,因为我们正在扫描所有图像。
如果您有很多图像,包大小会变得非常大,因为此解决方案会扫描所有 图像。
进一步定制
如果没有传递 Prop ,您可以调整代码以显示占位符图像。
备选方案
也就是说,there is another way you could tackle this ,但需要更多的工作/代码。
来源
- 我修改了 this article 中的代码. (请注意本文使用的是已弃用的代码。)
关于javascript - 具有动态图像源的可重用 Gatsby-Image 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55122752/