以视差效果的样式格式化 useref

formatting useref in style for paralax effect

我正在使用固定定位来尝试创建一个简单的视差效果

export const Home = () => {
    const paralaxref = React.useRef();


    const backdropImgStyle = {
        height: '200vh',
        position: 'fixed',
        top: paralaxref.current?.clientHeight? window.pageYOffset / paralaxref.current.clientHeight*-500 : 0,
        left: 0,
        zIndex: -100,
        filter: 'grayscale(.7)',
    }

但是,它不会在我滚动时更新我该怎么做?

---编辑---未来任何人的最终解决方案:

export const Home = () => {
    const paralaxref = React.useRef();

    const [paralaxPosition, setParalaxPosition] = React.useState(0);

    useEffect(() => {
        window.onscroll = () => {
            setParalaxPosition(paralaxref.current?.clientHeight? window.pageYOffset / paralaxref.current.clientHeight*-window.innerHeight : 0)
            //(returns 0-1 for percent scrolled)*(multiplier for image height)
        }
        }, [])


    const backdropImgStyle = {
        height: '200vh',
        width: '100vw',
        position: 'fixed',
        top: paralaxPosition,
        left: 0,
        right: 0,
        zIndex: -100,
    }
return(
<div ref={paralaxref} style={foregroundStyle}>
            <img style={backdropImgStyle}  
               src={"https://i.imgur.com/image.png"}/>

使用window.onScroll,然后更新其中的组件样式。这会起作用,但在 useEffect 中使用它,您可以在组件卸载时删除侦听器。

useEffect(() => {
window.onscroll = () => {
// add logic
}
}, []);