gpt4 book ai didi

javascript - Gatsby 插件图像无法读取属性 'startsWith'

转载 作者:行者123 更新时间:2023-12-05 06:03:26 28 4
gpt4 key购买 nike

在网站上没有找到这个,但我确实找到了 open bug on Github在撰写本文时,唯一的解决方案是使用 GatsbyImage。学习将 Gatsby 项目从 2 转换为 3 我已经安装了 gatsby-plugin-image并且正在转换一个在 Hero 组件中使用不变图像的组件,根据文档 StaticImage 应该可以工作。

旧组件:

import React from 'react'
import { graphql, useStaticQuery } from 'gatsby'
import Image from 'gatsby-image'


const query = graphql`
{
person: file(relativePath: {eq: "person.png"}) {
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
`

const Hero = ({ showPerson }) => {
const { person } = useStaticQuery(query)

return (
<header className="hero">
{showPerson && <Image fluid={person.childImageSharp.fluid} className="hero-person" />}
</header>
)
}

export default Hero

新组件:

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

import personImage from '../assets/person.png'

const Hero = ({ showPerson }) => {
console.log(personImage)
return (
<header className="hero">
{showPerson && <StaticImage src={personImage} className="hero-person" alt="person image" />}
</header>
)
}

export default Hero

当我记录我得到的 Assets 时(我的文件路径没有问题):

Hero.js:7 /static/person-c7035ca6b9544d80f8f0626ea3e22ace.png

但是日志呈现:

react_devtools_backend.js:2430 No data found for image "undefined"
Image not loaded /static/person-c7035ca6b9544d80f8f0626ea3e22ace.png

在终端我得到:

"gatsby-plugin-image" threw an error while running the preprocessSource lifecycle:

Cannot read property 'startsWith' of undefined

使用 Gatsby 图像 StaticImage 有没有一种方法可以在不使用 GatsbyImage 的情况下渲染一个在组件中不会改变的图像?

最佳答案

docs about the new Gatsby Plugin Image可以看出:

Restrictions on using StaticImage

The images are loaded and processed at build time, so there arerestrictions on how you pass props to the component. The values needto be statically-analyzed at build time, which means you can’t passthem as props from outside the component, or use the results offunction calls, for example. You can either use static values, orvariables within the component’s local scope. See the followingexamples:

所以,<StaticImage>组件无法处理 Prop 或函数调用来接收图像。在您的情况下,这应该有效:

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

const Hero = ({ showPerson }) => {
return (
<header className="hero">
{showPerson && <StaticImage src={`../assets/person.png`} className="hero-person" alt="person image" />}
</header>
)
}

export default Hero

由于您的 v2 相似方法,我建议使用 <GatsbyImage>而不是 <StaticImage> , 检查它是否符合您的要求。

对于迁移问题,Gatsby has developed a codemod处理所有 GraphQL 查询和“旧”gatsby-image s,更改所需的查询和组件。安装插件后,只需运行:

npx gatsby-codemods gatsby-plugin-image

这样,问题应该就解决了。如果没有,您可以在以下位置跟踪类似的堆栈跟踪:

看来这个问题与3.2.0-next.0有关版本,因此另一种选择是尝试降级(或升级,如果可能)。

关于javascript - Gatsby 插件图像无法读取属性 'startsWith',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66644333/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com