簡體   English   中英

如何使用 map function 和 Gatsby.js 正確渲染圖像

[英]How to properly render images using a map function with Gatsby.js

這個應用程序最初是使用 react 構建的,但是我們決定轉換一切並使用 Gatsbyjs。 我是 Gatsby 的新手,我正在嘗試使用藝術家數據正確渲染我的圖像。 以下是這部分數據最初是如何構建的:

const images = [
  AngelAndJaamiHeadshot,
  BillyHawkinsHeadshot,
  BostonWellsHeadshot,
  BreanahAlvizHeadshot,
  CarloCollantesHeadshot,
  CarloDarangHeadshot,
  ChrisLumbaHeadshot,
  ChrisMartinHeadshot,
  CJDelaVegaHeadshot,
  CyeBongalosHeadshot,
  DanielKimHeadshot,
  DavidDarkieSimmonsHeadshot,
  // DavidDiosoHeadshot,
  DavidSlaneyHeadshot,
  DavinLawsonHeadshot,
  DevinHeadshot,
  DustinYuHeadshot,
  EmilyRowanHeadshot,
  HonrieDualanHeadhot,
  HughAparenteHeadshot,
  JaamiWaaliVillalobosHeadshot,
  JeremyBorjaHeadshot,
  JonathanSisonHeadshot,
  JordanBautistaHeadshot,
  JordanRileyHeadshot,
  JuliaKestnerHeadshot,
  JustinArcegaHeadshot,
  KaitlynSungHeadshot,
  KaylarPrieteHeadshot,
  KeyanaReedHeadshot,
  KikoJamesHeadshot,
  KirstieAndJeremyHeadshot,
  KirstieHeadshot,
  KJEstudilloHeadshot,
  LarkinPoyntonHeadshot,
  MitchVillarealHeadhsot,
  MoanaRakanaceHeadshot,
  NoelleFrancoHeadshot,
  PhuongLeHeadshot,
  SamMooreHeadshot,
  TonyRayHeadshot,
  TracySeilerHeadshot,
  TrishaOcampoHeadshot,
  YutaNakamuraHeadshot,
  defaultHeadshot,
]

export const buildArtistsData = (artists) => {
  return artists.map((artist, idx) => {
    return {
      ...artist,
      imageUrl:
        idx >= 43
          ? defaultHeadshot
          : images[`${artist.firstName}${artist.lastName}Headshot`],
    }
  })
}

這就是它在我的 Artists 組件中的使用方式:

const ArtistsPage = () => {
 const artists = buildArtistsData(ARTISTS)

...

<div className={classes.flexContainer}>
          {artists
            .map(
              (
                { city, currentTeam, firstName, lastName, imageUrl },
                idx: number
              ) => {
                return (
                  <div className={classes.flexItem} key={idx}>
                    <img
                      className={classes.artistCardImg}
                      src={imageUrl}
                      alt='artist-image'
                    />
                    <div className={classes.artistCardName}>
                      {`${firstName} ${lastName}`.toUpperCase()}
                    </div>
                    <div className={classes.artistCardText}>{city}</div>
                    <div className={classes.artistCardText}>{currentTeam}</div>
                  </div>
                )
              }
            )}
        </div>

但是現在我正在使用 Gatsbyjs 和數據,以上都不再適用。 這是我在轉換后的 Gatsbyjs 頁面上使用的內容:

import React from 'react'
import PropTypes from 'prop-types'
import { StaticImage } from 'gatsby-plugin-image'
import Img from 'gatsby-image'
import { graphql } from 'gatsby'

import { useStyles } from './styles'

const ArtistsPage = ({ data }) => {
  console.log(data)
  const classes = useStyles()
  // const { images } = props

  return (
    <section>
      <article className={classes.artistsContainer}>
        <div className={classes.flexContainer}>
          {data.allArtistsJson.edges.map(({ node }, idx) => {
            return (
              <div className={classes.flexItem} key={idx}>
                <div>
                  {images.map((img, idx) => (
                    <Img
                      key={idx}
                      fluid={img.node.childImageSharp.fluid}
                    />
                  ))}
                </div>
                <div className={classes.artistCardName}>
                  {`${node.firstName} ${node.lastName}`.toUpperCase()}
                </div>
                <div className={classes.artistCardText}>{node.city}</div>
                <div className={classes.artistCardText}>{node.currentTeam}</div>
              </div>
            )
          })}
        </div>
      </article>
    </section>
  )
}
export const pageQuery = graphql`
  query {
    headshots: allFile(filter: { absolutePath: { regex: "/headshots/" } }) {
      edges {
        node {
          childImageSharp {
            fluid(maxWidth: 600) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`

ArtistsPage.propTypes = {
  firstName: PropTypes.string,
  lastName: PropTypes.string,
  currentTeam: PropTypes.string,
  headshots: PropTypes.string,
  dropdown: PropTypes.string,
  data: PropTypes.array,
  images: PropTypes.string,
}

export default ArtistsPage

我試圖使用 const { image } = props 將圖像數據作為道具拉取 - 但這會引發錯誤,所以我真的很困惑 map 是什么以及如何在此之上為正確的藝術家拉取我的圖像。

這里也是我的 config.js 文件供參考:

const path = require('path')

module.exports = {
  siteMetadata: {
    title: 'Platform Showcase',
  },
  plugins: [
    'gatsby-plugin-gatsby-cloud',
    'gatsby-plugin-image',
    // {
    //   resolve: "gatsby-plugin-google-analytics",
    //   options: {
    //     trackingId: "",
    //   },
    // },
    'gatsby-plugin-react-helmet',
    'gatsby-plugin-sitemap',
    {
      resolve: 'gatsby-plugin-manifest',
      options: {
        icon: 'src/images/icon.png',
      },
    },
    'gatsby-plugin-mdx',
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: './src/images/',
      },
      __key: 'images',
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `headshots`,
        path: `${__dirname}/src/images/artists/headshots`,
      },
      __key: 'headshots',
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'pages',
        path: './src/pages/',
      },
      __key: 'pages',
    },
    {
      resolve: 'gatsby-plugin-google-fonts',
      options: {
        fonts: ['material icons', 'roboto:300,400,500,700'],
      },
    },
    `gatsby-theme-material-ui`,
    `gatsby-transformer-json`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `./src/data/`,
      },
    },
    {
      resolve: 'gatsby-plugin-root-import',
      options: {
        src: path.join(__dirname, 'src'),
        containers: path.join(__dirname, 'src/containers'),
        images: path.join(__dirname, 'src/images'),
      },
    },
  ],
}

任何人願意提供的任何幫助將不勝感激。

使用頁面查詢時,您的數據始終位於props.data下,因此您的嵌套應如下所示:

      {data.headshots.edges.map(({ node }, idx) => {
        return (
          <div className={classes.flexItem} key={idx}>
            <Img fluid={node.childImageSharp.fluid} />
          </div>
        )
      })}

注意:我假設您的 GraphQL 查詢正確檢索數據。 localhost:8000/___graphql進行測試,並在需要時調整您的文件系統

每個圖像都是每個node本身(根據查詢結構),因此,由於您的查詢將allFile別名為headshots ,因此您的數據存儲在props.data.headshots中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM