当尝试在我的header.js中使用gatsby-image时,出现以下错误。
TypeError:未定义不是对象(正在评估“ props.data.flower”)
请参见下面的header.js代码。
import { Link } from "gatsby";
import PropTypes from "prop-types";
import React from "react";
import { graphql } from "gatsby";
import Img from "gatsby-image";
import bklogo from "../images/bk-logo-01.svg";
const Header = props => (
<nav className="bg-cover-image bg-repeat">
<div className="text-center sm:w-full relative pin">
<Img
fluid={props.data.flower.childImageSharp.fluid}
class="block mx-auto w-5/6 md:w-1/2"
alt="Brooke & Kyle"
/>
</div>
<div className="flex flex-wrap items-center justify-center max-w-3xl mx-auto px-8 py-0 md:px-8 md:py-3">
<Link
to="/"
className="flex items-center no-underline py-5 text-white w-1/2 sm:w-1/3 md:w-1/6"
>
<img src={bklogo} className="" alt="Brook & Kyle Logo" />
</Link>
</div>
</nav>
);
Header.propTypes = {
siteTitle: PropTypes.string
};
Header.defaultProps = {
siteTitle: ``
};
export default Header;
export const pageQuery = graphql`
query {
flower: file(relativePath: { eq: "flower-top.png" }) {
childImageSharp {
fluid(maxWidth: 1000) {
...GatsbyImageSharpFluid
}
}
}
}
`;
我的index.js中的gatsby图像工作正常。只是header.js有问题。
感谢您的帮助。
答案 0 :(得分:0)
在非页面组件(不在src/pages/
目录中的组件)中,导出的graphql查询将被忽略。您必须改用gatsby的StaticQuery
。
例如:
import { StaticQuery, graphql } from 'gatsby'
const Header = () => (
<StaticQuery
query={graphql`
query {
flower: file(relativePath: { eq: "flower-top.png" }) {
childImageSharp {
fluid(maxWidth: 1000) {
...GatsbyImageSharpFluid
}
}
}
}
`}
render={data => <Img fluid={data.flower.childImageSharp.fluid} />}
/>
)