我正在尝试使用 Gatsby 图像,但出现 Cannot read property 'childImageSharp' of null。我找不到错误在哪里。 Topsection.js 是一个底层组件。 image.jpg 位于 src/images/images.jpg 内部。仍然出现错误。
Topsection.js
const TopSection = () => {
const data = useStaticQuery(graphql`
{
featureimg: file(relativePath: { eq: "image.jpg" }) {
childImageSharp {
fluid(maxWidth: 60) {
...GatsbyImageSharpFluid
}
}
}
}
`);
return (
<>
<div className="first-post-thumbnail">
<a href="/best-keyboard-for-wow/">
<Image fluid={data.featureimg.childImageSharp.fluid} />
</a>
</div>
</>
);
};
export default TopSection;
35 | <div className="first-post-thumbnail">
36 | <a href="/best-keyboard-for-wow/">
37 |
> 38 | <Image fluid={data.featureimg.childImageSharp.fluid} />
| ^ 39 |
40 | </a>
41 | </div>
配置
/**
* Configure your Gatsby site with this file.
*
* See: https://www.gatsbyjs.com/docs/gatsby-config/
*/
module.exports = {
/* Your site config here */
siteMetadata: {
title: ``,
description: ``,
author: ``,
},
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-transformer-sharp`, `gatsby-plugin-sharp`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
resolve: `gatsby-plugin-prefetch-google-fonts`,
options: {
fonts: [
{
family: `Poppins`,
variants: [`200`,`300`,`400`,`500`,`600`,`700`, `900`]
},
],
},
},
],
}
编者注 2024 年 1 月 29 日:由于 gatsby-image 软件包已被弃用,以下答案应被视为已过时。仅当您正在维护代码或需要历史参考时才继续。
如果您正在构建新的,请参阅替换包: https://www.gatsbyjs.com/plugins/gatsby-plugin-image/
此行下方的原始答案。
假设您已正确设置文件系统并且图像可通过 GraphQL 访问。
尝试:
import Img from "gatsby-image"
// other imports
const TopSection = () => {
const data = useStaticQuery(graphql`
query {
featureimg: file(relativePath: { eq: "/images/image.jpg" }) {
childImageSharp {
fluid(maxWidth: 60) {
...GatsbyImageSharpFluid
}
}
}
}
`);
return <div className="first-post-thumbnail">
<a href="/best-keyboard-for-wow/">
<Img fluid={data.featureimg.childImageSharp.fluid} />
</a>
</div>;
};
export default TopSection;
文件节点的
relativePath
字段与您在 gatsby-source-filesystem
中指定的目录相关。
我建议使用
<Link>
组件而不是原生 <a>
(锚点)进行内部导航:
<Link to="/best-keyboard-for-wow/">
在 GraphQL 游乐场 (
localhost:8000/___graphql
) 中检查查询以检查拼写和结果。
清除缓存对我来说是成功的(除了删除 package-lock.json 并重新运行 npm install):
gatsby clean
清理项目并重新运行“npm install”工作
npm run clean
然后
npm install
图像应放置在 'static/images/image.jpg' 目录中,而不是 'src/images/image.jpg'。