我正在尝试使用gatsby-image构建一个react-bootstrap carousel,因为使用标准img标记的加载速度很慢。然而,我面临的问题是,我想为文件夹中的所有图像编写一个组件,而不是像gatsby-starter-default中那样为每个文件编写一个组件。因此,我希望Image组件返回一个图像数组,以便在<Image[0] />之类的Carousel中使用。或者将relativePath传递给旋转木马内部的组件,如<Image(carouselImages/carousel_1.jpeg) />
请看下面的carousel.js代码(为了可读性,减少到2张幻灯片)。
import React from 'react'
import Carousel from 'react-bootstrap/Carousel'
import Button from 'react-bootstrap/Button'
import './style.scss'
import { injectIntl, Link, FormattedMessage } from "gatsby-plugin-intl"
import Image1 from 'components/img1'
import Image2 from 'components/img2'
class ControlledCarousel extends React.Component {
constructor(props, context) {
super(props, context)
this.handleSelect = this.handleSelect.bind(this)
this.state = {
index: 0,
direction: null,
}
}
handleSelect(selectedIndex, e) {
this.setState({
index: selectedIndex,
direction: e.direction,
})
}
render() {
const { index, direction } = this.state
return (
<Carousel
activeIndex={index}
direction={direction}
onSelect={this.handleSelect}>
<Carousel.Item>
<div className="imgWrapper">
<Image1 />
</div>
<Carousel.Caption>
<p> some text </p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<div className="imgWrapper">
<Image2 />
</div>
<Carousel.Caption>
<p> some text </p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
)
}
}
export default ControlledCarousel以及Image组件本身:
import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
const Image = () => (
<StaticQuery
query={graphql`
query {
placeholderImage: file(relativePath: { eq: "carouselImages/carousel_1.jpg" }) {
childImageSharp {
fluid(maxWidth: 2500) {
...GatsbyImageSharpFluid
}
}
}
}
`}
render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
/>
)
export default Image对于如何让它们协同工作,有什么建议吗?非常感谢您的帮助。
发布于 2019-08-06 14:06:08
打开src/images中的一个文件夹,并将所有图片放在其中,然后使用StaticQuery中的过滤器来搜索该文件夹中的所有图片。
import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
import Img from 'gatsby-image';
import Carousel from 'react-bootstrap/Carousel';
export default () => (
<StaticQuery
query={graphql`
query {
allFile(filter: {relativeDirectory: {eq: "carousel"}}) {
edges {
node {
childImageSharp {
fluid(quality: 90) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`}
render={data=> (
<Carousel className="full-width-md d-none d-md-block">
{data.allFile.edges.map(pic =>
<Carousel.Item>
<Img fluid={pic.node.childImageSharp.fluid}/>
</Carousel.Item>
)}
</Carousel>
)}
/>
);https://stackoverflow.com/questions/56433537
复制相似问题