我在 Gatsbyjs 项目中有以下组件:
styleItem.js
import React from 'react'
import styled from 'styled-components'
import BackgroundImage from 'gatsby-background-image'
import {StaticQuery, graphql } from "gatsby"
import {Col } from 'react-bootstrap'
import '../styles/styles.css'
const StyleItem = (props) => {
return (
<StaticQuery
query={graphql`
query {
street: file(relativePath: { eq: "2.jpg" }) {
childImageSharp {
fluid(quality: 90, maxWidth: 1920) {
...GatsbyImageSharpFluid_withWebp
}
}
}
casual: file(relativePath: { eq: "3.jpg" }) {
childImageSharp {
fluid(quality: 90, maxWidth: 1920) {
...GatsbyImageSharpFluid_withWebp
}
}
}
athletic: file(relativePath: { eq: "3.jpg" }) {
childImageSharp {
fluid(quality: 90, maxWidth: 1920) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
`}
render={data => { Object.keys(data).map((image, i ) => {
console.log(props.stylesItem[image].name)
console.log(image)
return (
<Col md={4}>
<div class="style-box">
<StyledBackgroundImage
Tag="div"
className="style-box-img"
fluid={data[image].childImageSharp.fluid}
>
</StyledBackgroundImage>
<div class="style-text-box">
<h5 class="h5">{props.stylesItem[image].style}</h5>
<h3 class="h3 style-description">{props.stylesItem[image].name}</h3>
<div class="extra-style-details">
<p class="style-short-desc">{props.stylesItem[image].tagline}</p>
<p>{props.stylesItem[image].text}</p>
<ul class="hashtag-list">
<li class="style-attribut"></li>
</ul>
</div>
</div>
</div>
</Col>
)
})
}
}
/>
)
}
export default StyleItem
const StyledBackgroundImage = styled(BackgroundImage)`
background-size: cover;
background-position: center;
background-repeat: no-repeat;
`
我将以下道具传递给该组件(abc 虚拟字符串以提高可读性):
stylesItem: {
street: {
style: "// STREET",
name: "THE CANVAS",
tagline: "abc",
text: "abc",
hashtags: [
"abc", "abc", "abc", "abc"
]
},
casual: {
style: "// CASUAL",
name: "THE CLASSIC",
tagline: "abc",
text: "abc",
hashtags: [
"abc", "abc", "abc", "abc", "abc", "abc"
]
},
athletic: {
style: "// ATHLETIC",
name: "THE PERFORMER",
tagline: "abc",
text: "abc",
hashtags: [
"abc", "abc", "abc", "abc", "abc", "abc"
]
}
}
我正在使用 Gatsby 的 Staticquery 加载 3 张图像(街头、休闲、运动),并希望在第二个返回语句中渲染该部分 3 次(每个图像 1 次),每次都动态加载背景图像以及内容。
2 个 console.log() 语句按预期打印出来。
console.log(props.stylesItem[image].name)
console.log(image)
THE CANVAS
street
THE CLASSIC
casual
THE PERFORMER
athletic
然而,没有任何东西被渲染到屏幕上,我也没有看到任何错误。我究竟做错了什么?
在此先感谢您的帮助