Как включить карусельный компонент в Gatsby с Contentful? - PullRequest
2 голосов
/ 16 марта 2019

Я хочу включить карусель изображений в мой проект Gatsby. Все изображения будут запрашиваться из Contentful.

Я использовал «response-response-carousel» и смог заставить его работать с простым импортом изображений напрямую. Я также уверен, что смогу успешно загрузить содержательные изображения, не помещая их в компонент карусели.

Может кто-нибудь помочь мне с этим? Кажется, компонент gatsby-image Img не возвращает тег, который может распознать «response-reponsive-carousel». Или вы знаете какую-нибудь другую карусель, которая будет работать?

Мой код:

import React, { Component, Fragment } from "react"

import "react-responsive-carousel/lib/styles/carousel.min.css"
import { Carousel } from "react-responsive-carousel"
import { graphql } from "gatsby"
import Img from "gatsby-image"

import tourimg from "../images/tour-1.jpg"  //Import an image directly

export default class ApartmentPage extends Component {
  render() {
    const photos = this.props.data.allContentfulRooms.edges[0].node.photos
    return (
      <Carousel>
        {photos.map(photo => {
          const { fixed } = photo
          return (
            <div>
              <Img fixed={fixed} />
              {/* <img src={tourimg} /> */}
            </div>
          )
        })}
      </Carousel>
    )
  }
}

export const ROOM_QUERY = graphql`
  {
    allContentfulRooms {
      edges {
        node {
          id
          name
          photos {
            fixed(width: 150, height: 150) {
              ...GatsbyContentfulFixed_tracedSVG
            }
          }
        }
      }
    }
  }
`
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Сообщение об ошибке:

TypeError: Cannot read property 'map' of null
Thumbs.renderItems
node_modules/react-responsive-carousel/lib/components/Thumbs.js:174
  171 | value: function renderItems() {
  172 |     var _this2 = this;
  173 | 
> 174 |     return this.state.images.map(function (img, index) {
  175 |         var itemClass = _cssClasses2.default.ITEM(false, index === _this2.state.selectedItem && _this2.state.hasMount);
  176 | 
  177 |         var thumbProps = {

1 Ответ

0 голосов
/ 26 июля 2019

Ошибка, которую вы видите, связана с компонентом thumbs react-responsive-carousel.Хотя компонент может обслуживать любой контент в дочерних элементах div, однако для работы миниатюр требуется тег img.Поскольку с gatsby вам нужно работать с компонентом <Img>, это можно исправить, отключив миниатюры

<Carousel showThumbs={false} />

Ниже приведен полный рабочий пример (используется Typescript):

import * as React from "react";
import Img from "gatsby-image";
import { graphql, StaticQuery } from "gatsby";

import "react-responsive-carousel/lib/styles/carousel.min.css";
import { Carousel } from "react-responsive-carousel";


interface childImageSharpNode {
  childImageSharp: {
    fluid: any;
  };
}
interface SlideShowComponentProps {
  nodes: childImageSharpNode[];
}

class SlideShowComponent extends React.Component<SlideShowComponentProps> {
  constructor(props: SlideShowComponentProps) {
    super(props);
  }

  render() {
    const images: any[] = [];
    for (const node of this.props.nodes) {
      images.push(
        <div>
          <Img fluid={node.childImageSharp.fluid} alt="Image"></Img>
        </div>,
      );
    }

    return (
      <Carousel showThumbs={false} infiniteLoop={true} autoPlay={true}>
        {images}
      </Carousel>
    );
  }
}

interface StaticQueryProps {
  allFile: {
    nodes: childImageSharpNode[];
  };
}

const SlideShow: React.FC = () => (
  <StaticQuery
    query={graphql`
      query slideshow {
        allFile(filter: { relativePath: { regex: "/slideshow/" } }) {
          nodes {
            childImageSharp {
              fluid(maxWidth: 1024) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    `}
    render={(data: StaticQueryProps) => <SlideShowComponent nodes={data.allFile.nodes}></SlideShowComponent>}
  />
);

export default SlideShow;
...