繁体   English   中英

在 Gatsby.js 中处理图像本地文件

[英]Working with images local files in Gatsby.js

我正在尝试为页面上显示的每个艺术家渲染头像。 艺术家数据来自 Json 文件,图像位于 images/artists/headshots 中。 我正在使用常规的 img 标签,但由于某种原因,页面上没有显示任何内容。 任何人都可以提供的任何帮助将不胜感激。

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

import { useStyles } from './styles'

const ArtistsPage = ({ data }) => {
  const classes = useStyles()

  return (
    <section>
      <article className={classes.artistsBackground}>
        <div className={classes.heroLayoutContainer}>
          <h3 className={classes.title}>MEET THE ARTISTS</h3>

          <StaticImage
            className={classes.heroImage}
         src='../../images/artists/hero-images/hero-image-artists.jpg'
            alt='hero-image-artists'
            placeholder='blurred'
          />
        </div>
      </article>
      <article className={classes.artistsContainer}>
        <div className={classes.flexContainer}>
          {data.allArtistsJson.edges
            .map(({ node }, idx) => {
              const artist = `${node.firstName}+${node.lastName}`
                .split('+')
                .join(' ')

              return (
                <div className={classes.flexItem} key={idx}>
                  <div>
                    <img
                      src={`../../images/artists/headshots/${artist} Headshot.jpg`}
                      alt='artist-headshot'
                    />
                  </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 default ArtistsPage

我的图像文件设置为:FirstName LastName Headshots.jpg

我认为您的问题可能来自命名中的空格。 您的代码乍一看还不错,因此请尝试使用下划线或驼峰命名法重命名您的图像:

   <img
      src={`../../images/artists/headshots/${artist}_Headshot.jpg`}
      alt='artist-headshot'
    />

经过大量研究和 Gatsby discord 上的好人之后,我发现答案是……在这样的场景中,我需要添加 require().default。
例如:<img src={require( ../../images/artists/headshots/${artist} Headshot.jpg ).default} alt='artist-headshot' />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM