gpt4 book ai didi

javascript - Gatsby :getImage 返回未定义

转载 作者:行者123 更新时间:2023-12-05 04:29:32 27 4
gpt4 key购买 nike

getImage 返回未定义,因此我的 GatsbyImage 组件未呈现。

文件结构:

  • src/pages/gallery.js
  • src/images(有 12 张照片,名为 photo-01.jpg、photo-02.jpg、...)

我有以下代码 (gallery.js):

import React from "react";
import Layout from "../components/Layout";
import { useStaticQuery, graphql } from "gatsby";
import { GatsbyImage, getImage } from "gatsby-plugin-image";

const Gallery = () => {
const { gallery } = useStaticQuery(graphql`
query {
gallery: allFile(
filter: {
extension: { eq: "jpg" }
absolutePath: { regex: "/images/" }
}
) {
nodes {
id
childImageSharp {
fluid(maxWidth: 500, maxHeight: 500) {
...GatsbyImageSharpFluid_tracedSVG
}
}
}
}
}
`);

return (
<Layout>
<div className="container py-5">
<div className="row">
<div className="col-12">
<h1 className="text-gastby mb-4">Gallery</h1>
</div>
</div>
<div className="row">
{gallery.nodes.map((image) => (
<div className="col-lg-3 col-md-4 col-sm-6 mb-3" key={image.id}>
<GatsbyImage
image={getImage(image.childImageSharp.fluid)}
alt="Gallery"
/>
</div>
))}
</div>
</div>
</Layout>
);
};

export default Gallery;

我有什么问题吗?

最佳答案

问题是你在混合 gatsby-image (从 Gatsby 1 到 Gatsby 2)和 gatsby-plugin-image (从 Gatsby 3 开始)。第一个现已弃用。

当您查询 fluid 时很容易发现这一点或 fixed GraphQL 节点,因为它们是由 gatsby-image 创建的使用Img ( from 'gatsby-image ') 组件,它接受 fluidfixed属性(property)。

另一方面,gatsby-plugin-image查询 gatsbyImageData (不是 fluidfixed )和相应的 GatsbyImage ( from 'gatsby-plugin-image' ) 组件接受 image属性(property)。

在您的例子中,您正在查询 gatsby-image结构应用于 gatsby-plugin-image组件,这就是它返回 undefined 的原因.

检查 migration guide但基本上您需要替换(并删除)所有对 gatsby-image 的引用并安装所需的依赖项:

npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-transformer-sharp

将其添加到您的 gatsby-config.js :

module.exports = {
plugins: [
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
],
}

并将您的查询更改为:

const Gallery = () => {
const { gallery } = useStaticQuery(graphql`
query {
gallery: allFile(
filter: {
extension: { eq: "jpg" }
absolutePath: { regex: "/images/" }
}
) {
nodes {
id
childImageSharp {
gatsbyImageData(layout: FIXED)
}
}
}
}
`);

return (
<Layout>
<div className="container py-5">
<div className="row">
<div className="col-12">
<h1 className="text-gastby mb-4">Gallery</h1>
</div>
</div>
<div className="row">
{gallery.nodes.map((image) => (
<div className="col-lg-3 col-md-4 col-sm-6 mb-3" key={image.id}>
<GatsbyImage
image={getImage(image.childImageSharp)}
alt="Gallery"
/>
</div>
))}
</div>
</div>
</Layout>
);
};

export default Gallery;

仔细检查查询,因为在应用 gatsby-plugin-image 时节点和结构可能不同.

请注意 getImage 是一个辅助函数,你可能不需要它,考虑直接使用:

  <GatsbyImage
image={image.childImageSharp.gatsbyImageData}
alt="Gallery"
/>

关于javascript - Gatsby :getImage 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72298629/

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