我在React中实现背景图像中的视差滚动时遇到问题,如有帮助,不胜感激。
我得到的错误是:
TypeError:无法读取空的属性"style">
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