我已安装gatsby-plugin-layout
来保持Layout组件的持久性。在“布局”组件中,我有一个名为“ RandomBackground”的组件,该组件正是这样做的,它在页面加载时显示了随机的背景图像。
但是,在随后的页面更改中背景图像也会更改,这是不希望的行为。
我在做什么错?以下为简明代码。
gatsby-config.js
{
resolve: `gatsby-plugin-layout`,
options: {
component: require.resolve(`./src/components/Layout`),
},
}
布局
const Layout = ({ children }) => {
return (
<>
<Content>
<main>{children}</main>
</Content>
<RandomBackground />
</>
)
}
RandomBackground
import React from 'react'
import Image from 'gatsby-image'
import { useStaticQuery, graphql } from 'gatsby'
import styled from '@emotion/styled'
const BackgroundImg = styled(Image)`
object-fit: cover;
width: 100vw;
height: 100vh;
`
const randomGenerator = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min
}
const RandomBackground = () => {
const data = useStaticQuery(graphql`
query ImageQuery {
wordPress {
pageBy(uri: "home") {
homeFields {
backgroundImage {
images {
sourceUrl
imageFile {
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
}
}
`)
const images = data.wordPress.pageBy.homeFields.backgroundImage.images
const randomPosition = randomGenerator(0, images.length - 1)
const randomizedImage = images[randomPosition].imageFile.childImageSharp
console.log('render') // pops up in console every page change
return (
<BackgroundImg fluid={randomizedImage.fluid} />
)
}
答案 0 :(得分:1)
您的背景图片随着“页面更改”而改变,因为每次页面更改时,您的Layout
组件都会重新呈现。
为了保留您的背景图片,请按照以下方式将生成的随机数存储在RandomBackground
上:
import {useState} from 'react';
...
const RandomBackground = () => {
const data = useStaticQuery(graphql`
query ImageQuery {
wordPress {
pageBy(uri: "home") {
homeFields {
backgroundImage {
images {
sourceUrl
imageFile {
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
}
}
`)
const images = data.wordPress.pageBy.homeFields.backgroundImage.images
const randomPositionInitial = randomGenerator(0, images.length - 1);
const [randomPosition] = useState(randomPositionInitial);
const randomizedImage = images[randomPosition].imageFile.childImageSharp
console.log('render') // pops up in console every page change
return (
<BackgroundImg fluid={randomizedImage.fluid} />
)
}