我正在尝试将工具栏背景颜色更改为#fff正文滚动时的颜色。否则它将是transparent.这是示例工具栏组件: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> ) }}我们如何通过反应来做到这一点?
1 回答

狐的传说
TA贡献1804条经验 获得超3个赞
只需将事件侦听器添加到窗口对象即可。
componentDidMount() {
window.addEventListener('scroll', this.checkScroll);
}
checkScroll = () => {
this.setState({ scrolled: window.scrollY > 0 });
};
注意:您可能还需要一些去抖动以避免快速和多个设置状态。
并记住在组件销毁时断开侦听器。
componentWillUnmount() {
window.removeEventListener('scroll', this.checkScroll);
}
添加回答
举报
0/150
提交
取消