Gatsby-Image 및 React Hooks로 슬라이드쇼 만들기

GatsbyJS는 최근 제가 가장 좋아하는 기술 중 하나입니다. 프론트엔드 개발을 다시 즐겁게 만들었습니다.
최근에 others 비슷한 문제가 발생한 것 같습니다. 즉, 슬라이드쇼/캐러셀/여러 이미지를
gastbyjs 및 gatsby-image .TLDR; I built a "slideshow" of lazy loaded images, demo over at gatsby-slides
면책 조항: 이것은 꽤 실험적이고 해키적이며 개선될 수 있다고 확신합니다. 비평을 환영합니다.
Gatsby 및 Gatsby-Image 설정
gatsby 문서가 매우 잘 작성되었기 때문에 기본 프로젝트를 시작하고 설정하는 것이 상당히 쉽습니다. 터미널에서 다음을 입력하십시오.$ gatsby new gatsby-slide
$ cd gatsby-slide
이렇게 하면 시작 템플릿에서 새 gatsby 프로젝트(
gatsby-image가 이미 설치됨)가 생성되고 gatsby가 파일 설정을 완료한 후 디렉터리가 변경됩니다.이제
npm start를 실행하고 localhost:8000으로 이동하면 gatsby 사이트가 실행되고 있는 것을 볼 수 있습니다.계속할 준비가 되었습니다!
여러 이미지 쿼리
고맙게도 템플릿에는 아래와 같이 이미 이미지를 쿼리하는 코드가 포함되어 있습니다.
//src/image.js
const Image = () => (
  <StaticQuery
    query={graphql`
      query {
        placeholder: file(relativePath: { eq: "gatsby-logo.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => <Img fluid={data.placeholder.childImageSharp.fluid} />}
  />
)
그러면 이미지
gatsby-logo.png가 검색되고 지연 로드됩니다.조각
GatsbyImageSharp , 조각 및 gatsby-image here 에 대해 자세히 읽어보십시오. 하지만 우리는 어떻게이것을 사용하여 여러 이미지를 쿼리합니까? Kent C. Dodds 덕분에 저번에 책을 읽다가 이 작은 보석을 발견했습니다.
graphql`
  query {
    allFile(
      sort: { fields: name, order: DESC }
      filter: { relativeDirectory: { eq: "slides" } }
    ) {
      edges {
        node {
          id
          name
          childImageSharp {
            fluid(maxWidth: 600) {
              ...GatsbyImageSharpFluid_withWebp_tracedSVG
            }
          }
        }
      }
    }
  }
이제 여러 파일을 가져오기 위한 이 쿼리가 있으므로 계속해서 이를 좋은 ol 후크로 연결해 보겠습니다.
import { useStaticQuery, graphql } from 'gatsby'
function SlideShow() {
  const [index, setIndex] = useState(0)
  const { allFile } = useStaticQuery(
    graphql`
      query {
        allFile(
          sort: { fields: name, order: DESC }
          filter: { relativeDirectory: { eq: "slides" } }
        ) {
          edges {
            node {
              id
              name
              childImageSharp {
                fluid(maxWidth: 600) {
                  ...GatsbyImageSharpFluid_withWebp_tracedSVG
                }
              }
            }
          }
        }
      }
    `
  )
  //Minus 1 for array offset from 0
  const length = allFile.edges.length - 1
  const handleNext = () =>
    index === length ? setIndex(0) : setIndex(index + 1)
  const handlePrevious = () =>
    index === 0 ? setIndex(length) : setIndex(index - 1)
  const { node } = allFile.edges[index]
  return (
    <div>
      <div>
        <Img
          fluid={node.childImageSharp.fluid}
          key={node.id}
          alt={node.name.replace(/-/g, ' ').substring(2)}
        />
      </div>
      <div>
        <button onClick={() => handlePrevious()}>Previous</button>
        <button onClick={() => handleNext()}>Next</button>
      </div>
    </div>
  )
}
다음 및 이전 슬라이드를 처리하기 위한 몇 가지 추가 논리가 있지만 전반적으로 여전히 간단한 예입니다.
결론
React Hooks 및 graphql의 신비로운 힘을 통해 우리는
useStaticQuery 후크도 할 수 있습니다.allFiles 폴더에 있는 모든 이미지를 가져오기 위해 쿼리하기 위해 slides에 필터를 지정하는 것과 같이(슬라이드 쇼의 모든 이미지가 있는 곳, duh Jordan). 결과는 매우 간단합니다. 데모gatsby-slides를 확인하십시오.Did this interest you? Head over to jordnjones.com for more!
Reference
이 문제에 관하여(Gatsby-Image 및 React Hooks로 슬라이드쇼 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/pr0x1ma/building-a-slideshow-with-gatsby-image-and-react-hooks-4ajf텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)