我正在尝试在主体滚动时将工具栏背景颜色更改为 #fff
颜色。否则它将是透明
。
这是示例工具栏组件:
export default class ToolBar extends React.Component {
constructor(props){
super(props)
this.state = {
scrolled:false
}
}
render() {
const { children, className,scrolled, ...other } = this.props
return (
<nav style={{backgroundColor:this.state.scrolled?'#fff':'transparent'}}>
{children}
</nav>
)
}
}
我们如何用 React 做到这一点?
最佳答案
只需向窗口对象添加一个事件监听器。
componentDidMount() {
window.addEventListener('scroll', this.checkScroll);
}
checkScroll = () => {
this.setState({ scrolled: window.scrollY > 0 });
};
注意:您可能还需要一些去抖动以避免快速和多重设置状态。
并记得在组件销毁时断开监听器。
componentWillUnmount() {
window.removeEventListener('scroll', this.checkScroll);
}
关于javascript - 更改工具栏背景颜色并在 body 滚动时使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59148413/