我有一个组件,我想在用户滚动页面时更改背景颜色
这是我尝试过的
const [mainColor, setMainColor] = useState('red')
const listenScrollEvent = () => {
window.scrollY < 10
? setMainColor('green')
: setMainColor('red')
}
useEffect(() => {
window.addEventListener('scroll', listenScrollEvent)
})
return (
<main className={cx(classes.content, { [classes.disableScroll]: show })}
style={{ backgroundColor: mainColor }}
>
{children}
</main>
)
这是供您参考的 css 类
content: {
backgroundColor: theme.colors.gray[0],
position: 'fixed',
top: params.headerHeight,
right: 0,
left: 0,
bottom: 0,
overflowY: 'auto',
[mq(theme.breakpoints.sm)]: {
right: 0,
left: params.sidebarCollapsedWidth
}
有人可以帮我弄清楚为什么
window.scrollY
不起作用吗?我已经尝试过console.log(window.scrollY)
,看看控制台上是否有任何东西,但我也没有得到任何东西,也无法弄清楚我在这里做错了什么。就像专家的帮助
提前致谢
当我查看您的代码时,我最初的想法是您可能有错误
useEffect
。话虽如此,如果没有看到代码的运行情况,就很难判断到底出了什么问题。我创建了一个快速尖峰,它主要反映了您上面的示例,并且它实现了您的预期:
import { useState, useEffect } from 'react';
import reactLogo from './assets/react.svg';
import viteLogo from '/vite.svg';
import './App.css';
const INIT_COLOR = "purple"
function App() {
const [color, setColor] = useState(INIT_COLOR);
const listenScrollEvent = () => {
setColor(window.scrollY < 10 ? INIT_COLOR : "gray");
};
useEffect(() => {
window.addEventListener('scroll', listenScrollEvent);
}, []);
return (
<>
<div style={{ backgroundColor: color }}>
<a href="https://vitejs.dev" target="_blank" style={{ paddingBottom: "1000px" }}>
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
</>
);
}
export default App;
这是上面代码的实际演示: https://www.loom.com/share/46435ccb648f44d498eee453f7820ec8?sid=c3bd2595-270e-47b5-a452-ac4efdc431c8