gpt4 book ai didi

javascript - React 中的视差滚动

转载 作者:行者123 更新时间:2023-12-04 08:21:04 27 4
gpt4 key购买 nike

我在 React 的背景图像中实现视差滚动时遇到问题,任何帮助将不胜感激。
我得到的错误是:

TypeError: Cannot read property 'style' of null


function Hero() {
const parallax = document.getElementById('home');
window.addEventListener('scroll', function() {
let offset = window.pageYOffset;
parallax.style.backgroundPositionY = offset * .12 + 'px';
})
return (
<div className="hero-container" id='home'>
<p className='title'>The Burger Shop</p>
</div>
)
}
export default Hero
.hero-container {
height: 100vh;
background-image: url('burger2.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
background-attachment: fixed;
}

最佳答案

在您运行 getElementById 时该元素尚未安装.
您将需要使用 ref (使用 useRef )并且您还需要在取消安装元素后删除事件监听器。您将需要 useEffect 为了这

function Hero() {
const parallax = React.useRef(null);

React.useEffect(() => {
function scrollHandler() {
const element = parallax.current;
if (element) {
let offset = window.pageYOffset;
element.style.backgroundPositionY = offset * .12 + 'px';
}
}
window.addEventListener('scroll', scrollHandler)
// return the function to remove the handler
// which will be run whn Hero is unmounted
return () => window.removeEventListener('scroll', scrollHandler);
}, []);

return (
<div className="hero-container" id='home' ref={parallax}>
<p className='title'>The Burger Shop</p>
</div>
)
}
export default Hero

演示在 https://codesandbox.io/s/epic-water-fx5rb

关于javascript - React 中的视差滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65498890/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com