【问题标题】:GatsbyJS - Relative img tag src that point to specific directory/sourceGatsbyJS - 指向特定目录/源的相对 img 标签 src
【发布时间】:2021-12-18 06:36:07
【问题描述】:

我正在尝试使用 GatsbyJS 创建一个静态站点,我需要解析 img 标签,以便相对 URLs 指向某个目录,而绝对目录(以 @987654322 开头@工作正常)。
我试过制作一个合适的组件,但由于它不是 页面Graphql 将无法运行:

import React from "react"
import { graphql } from "gatsby"

// Component constants
const absUrlRex = new RegExp(/^https?:\/\//, "i")

// Component
const CustomImg = ({ src, data, ...props }) => {
    let imgSrc = src
    if (!absUrlRex.test(src)) {
        if (null !== data.file) {
            imgSrc = data.file.publicURL
        } else {
            console.log(`Image "${src}" NOT found!`)
        }
    }

    return <img src={imgSrc} {...props} />
}

export default React.memo(
    CustomImg,
    (prev, next) => next.src === prev.src
)

export const query = graphql`
    query($src: String!) {
        file (
            sourceInstanceName: {eq: "images"},
            relativePath: {eq: $src}
        ) {
            publicURL
        }
    }
`

我已经尝试过“gatsby-plugin-image”的StaticImage,但是src参数不是静态字符串,所以不起作用。

【问题讨论】:

    标签: javascript reactjs image gatsby gatsby-image


    【解决方案1】:

    您正在组件中运行page query。这永远不会起作用,因为页面查询仅适用于顶级组件(页面),因此得名。

    因为您使用的是动态 GraphQL 过滤器参数 ($src: String!),而使用 static query 不是一个选项(它们不接受动态参数,因此得名),因此您唯一的机会是将查询移动到页面组件并将file作为道具深入到组件中。

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 2015-10-02
      • 2010-09-12
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 2019-11-23
      相关资源
      最近更新 更多