如何解决Gatsby背景图片无法在特定屏幕尺寸下渲染文本
我正在创建一个投资组合的主页,并且我希望在背景图像的前面有文本,该文本根据用户屏幕的大小而变化。现在,图像根据用户的屏幕尺寸而改变;但是,如果屏幕太小或以不同的屏幕尺寸开始加载,则前面的文本会消失。
import 'bootstrap/dist/css/bootstrap.min.css'
import BackgroundImage from "gatsby-background-image"
import '../styles/global.scss';
import { graphql,useStaticQuery } from "gatsby"
export default function MainPage() {
const size = useWindowSize();
const data = useStaticQuery(graphql`
query {
background: file(relativePath: {eq: "image.png"}) {
childImageSharp {
fluid(maxWidth: 2000) {
...GatsbyImageSharpFluid
...GatsbyImageSharpFluidLimitPresentationSize }
}
}
backgroundMed: file(relativePath: {eq: "image-med.png"}) {
childImageSharp {
fluid(maxWidth: 800) {
...GatsbyImageSharpFluid
...GatsbyImageSharpFluidLimitPresentationSize }
}
}
backgroundSm: file(relativePath: {eq: "image-sm.png"}) {
childImageSharp {
fluid(maxWidth: 600) {
...GatsbyImageSharpFluid
...GatsbyImageSharpFluidLimitPresentationSize }
}
}
}
`)
let sizeImg;
let width = size.width;
if (width < 533) {
sizeImg = data.backgroundSm.childImageSharp.fluid;
} else if (width < 656) {
sizeImg = data.backgroundMed.childImageSharp.fluid;
} else {
sizeImg = data.background.childImageSharp.fluid;
}
console.log(sizeImg);
return (
<BackgroundImage id={`background-intro`} fluid={sizeImg}>
<div id="header" className="flex" data-sal="fade">
<div id="main"></div>
<br />
<h1>Hey,welcome to my site.</h1>
<h3> Sample text</h3>
<br />
</div>
<br />
<br />
<br />
</div>
</BackgroundImage>
);
}
function useWindowSize() {
// Initialize state with undefined width/height so server and client renders match
// Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
const [windowSize,setWindowSize] = useState({
width: undefined,height: undefined,});
useEffect(() => {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,height: window.innerHeight,});
}
// Add event listener
window.addEventListener("resize",handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
return () => window.removeEventListener("resize",handleResize);
},[]); // Empty array ensures that effect is only run on mount
return windowSize;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。