如何在react.js中更改滚动上的CSS属性?(反应新手)



我正在尝试更改"底部"属性,并在滚动时创建视差效果。这可以在香草JS中通过添加滚动监听器轻松完成,但react有很多工作部分,我想知道做这件事的最佳方式是不是内存密集型?我有一个基于window.scrollY计算的新值。这是我迄今为止使用use/setState((计算的值,但滚动事件甚至不会触发。

import { useState } from 'react';
import './App.css';
function App() {
const [scroll, setScroll] = useState(0)
const map = (value, x1, y1, x2, y2) => (value - x1) * (y2 - x2) / (y1 - x1) + x2;
function handleScroll() {
console.log('scroll')
let yScroll = window.scrollY;
let minS = 0;
let maxS = document.body.scrollHeight;
let minB = 5 * 50;
let maxB = 38 * 50;
let newBottom = map(yScroll, minS, maxS, minB, maxB)
setScroll(newBottom)
}
return (
<div onScroll={handleScroll} className="App">
<div className="container">
<div className="wrapper" style={{bottom: scroll}}>
<div style={{top: '2em'}} className="disc"></div>
<div style={{top: '4em'}} className="disc"></div>
<div style={{top: '6em'}} className="disc"></div>
</div>
</div>
</div>)
)} 
export default App;

CSS

.container  {
width: 100vw;
height: 200vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 50px;
perspective-origin: center;
perspective: 17em;
overflow: hidden;
}

.wrapper {
bottom: 200px;
transform-style: preserve-3d;
transition: all 0.2s ease;
}
.disc {
position: absolute;
transform:
translate(-50%, -50%) rotateX(80deg) scale(1);
width: 10em;
height: 10em;
transform-style: preserve-3d;
background-image: url('./img/cd3.png');
background-size: 100% 100%;
}

我设法根据指向我答案的注释解决了它,这可能对内存不好。使用Use Effect,然后调用其中的滚动侦听事件。

const [scroll, setScroll] = useState(0)

useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, [])
function handleScroll() {
let yScroll = window.scrollY;
let minS = 0;
let maxS = document.body.scrollHeight;
let minB = 5 * 50;
let maxB = 38 * 50;
let newBottom = map(yScroll, minS, maxS, minB, maxB)
setScroll(newBottom)
}
<div className="wrapper" style={{bottom: scroll}}>
<div style={{top: '2em'}} className="disc"></div>
<div style={{top: '4em'}} className="disc"></div>
<div style={{top: '6em'}} className="disc"></div>
<div style={{top: '8em'}} className="disc"></div>
</div>

最新更新