我认为在这一点上我已经看了太长时间,可能看不到明显的东西,但是我无法弄清楚为什么我的查询不能正确获取背景图像数据,而是显示为空。我正在使用package.json中加载的"gatsby-background-image": "^1.1.1"
。我在这样的gatsby-config.js中引用图像文件:
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
以及使用它的组件:
import React from 'react';
import { graphql, StaticQuery } from 'gatsby';
import styled from 'styled-components';
import BackgroundImage from 'gatsby-background-image';
const BackgroundSection = () => (
<StaticQuery
query={graphql`
query {
desktop: file(relativePath: { eq: "demo.jpg" }) {
childImageSharp {
fluid(quality: 90, maxWidth: 1920) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
`}
render={data => {
/* eslint-disable no-console */
console.log(data);
/* eslint-enable no-console */
// Set ImageData.
const imageData = data.desktop.childImageSharp.fluid;
return (
<BackgroundImage
Tag="section"
fluid={imageData}
backgroundColor={`#040e18`}
>
<h2>gatsby-background-image</h2>
</BackgroundImage>
);
}}
/>
);
const StyledBackgroundSection = styled(BackgroundSection)`
width: 100%;
background-position: bottom center;
background-repeat: repeat-y;
background-size: cover;
`;
export default StyledBackgroundSection;
我想念什么?
答案 0 :(得分:1)
更改了一些语法以使其更现代,同时更新了一些依赖项,因此,老实说,我不完全确定是什么解决了该问题,但是这里是我的github compare,用于显示何时通过测试以及何时通过测试。最初,这种新语法似乎也不起作用,但最终确实通过了数据传递。
万一有人好奇我的bgimage.js
代码最终看起来像这样:
import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import styled from 'styled-components';
import BackgroundImage from 'gatsby-background-image';
import { theme } from '@styles';
const { colors } = theme;
/**
* In this functional component a fullscreen <BackgroundImage /> is created.
* @param className string className(s) from styled-components.
* @param children nodes Child-components.
* @return {*}
* @constructor
*/
const FullBackground = ({ children }) => {
const { desktop } = useStaticQuery(
graphql`
query {
desktop: file(relativePath: { eq: "bg/pompidou.jpg" }) {
childImageSharp {
fluid(quality: 90, maxWidth: 3024) {
...GatsbyImageSharpFluid_withWebp_tracedSVG
}
}
}
}
`);
// Watch out for CSS's stacking order, especially when styling the individual
// positions! The lowermost image comes last!
const backgroundFluidImageStack = [
desktop.childImageSharp.fluid,
`linear-gradient(${colors.alphaNavy}, ${colors.alphaNavy})`,
].reverse();
return (
<BackgroundImage
Tag="section"
fluid={backgroundFluidImageStack}
title="Fullscreen Background"
id="fullscreenbg"
role="img"
aria-label="Fullscreen Background"
preserveStackingContext={true}
style={{
// Defaults are overwrite-able by setting one of the following:
backgroundSize: 'cover',
backgroundPosition: 'center center',
// backgroundRepeat: '',
backgroundAttachment: 'fixed',
}}
>
{children}
</BackgroundImage>
);
};
const StyledFullBackground = styled(FullBackground)`
`;
export default StyledFullBackground;```