Ign*_*ška 2 image-loading reactjs webpack gatsby
我正在使用 GatsbyJS starter https://www.gatsbyjs.org/starters/codebushi/gatsby-starter-forty/并需要在页面上显示目录中的所有图片。Gatsby 推荐的导入媒体的方法是使用import
语句,但这会导致在构建后将哈希值添加到文件名中。例如:
/static/pic09-d59e4b49832baeb9c62a7a9d6c070f8c.jpg
如果我从目录中检索所有文件名并尝试用它创建<img>
元素src={fileName}
,则会产生空图像,因为文件名与服务器中已附加哈希值的文件名不匹配。
请推荐一个优雅的解决方案来解决这个问题。我的备份计划是将所有内容放入static
未添加哈希值的目录中,但 Gatsby 文档不推荐这样做:https://www.gatsbyjs.org/docs/static-folder/
这就是我现在所拥有的:
import React from 'react'
import Layout from '../components/layout'
class Gallery extends React.Component {
render() {
const images = [];
const req = require.context('../assets/images/signboards', false);
req.keys().forEach(function (key) {
images.push(key.substr(1));
});
return (
<Layout>
<div id="main">
<section className="spotlights">
<section>
{images.map((image) => {
return (
<div className="image">
<img src={'../assets/images/signboards' + image} alt="" />
</div>
)
})}
</section>
</section>
</div>
</Layout>
)
}
}
export default Gallery;
Run Code Online (Sandbox Code Playgroud)
谢谢
注意:此答案假设您已经安装了gatsby-source-filesystem
、gatsby-transformer-sharp
和gatsby-plugin-sharp
。
allFile
您可以使用 graphql 页面查询通过正则表达式匹配器的组合进行过滤来获取特定文件夹中特定扩展名的所有文件。
然后您可以循环遍历生成的边缘并用于gatsby-image
显示图像。
import React from "react"
import { graphql } from "gatsby"
import Img from 'gatsby-image'
const IndexPage = ({data}) => (
<>
{data.allFile.edges.map(edge => {
return <Img fluid={edge.node.childImageSharp.fluid} />
})}
</>
)
export default IndexPage
export const indexQuery = graphql`
query AssetsPhotos {
allFile(filter: {extension: {regex: "/(jpg)|(jpeg)|(png)/"}, dir: {regex: "/assets/images/signboards"}}) {
edges {
node {
id
childImageSharp {
fluid(maxWidth: 300) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2978 次 |
最近记录: |