我正在使用 bootstrap 4 导航栏,想在 ig 400px 向下滚动后更改背景颜色。我正在查看反应文档并找到了一个 onScroll 但找不到那么多信息。到目前为止我有…
我不知道我是否使用了正确的事件侦听器或如何设置高度等。
而且我并没有真正设置内联样式……
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = { scrollBackground: 'nav-bg' };
this.handleScroll = this.handleScroll.bind(this);
}
handleScroll(){
this.setState ({
scrollBackground: !this.state.scrollBackground
})
}
render() {
const scrollBg = this.scrollBackground ? 'nav-bg scrolling' : 'nav-bg';
return (
<div>
<Navbar inverse toggleable className={this.state.scrollBackground}
onScroll={this.handleScroll}>
...
</Navbar>
</div>
);
}
}
export default App;
原文由 Fernando B 发布,翻译遵循 CC BY-SA 4.0 许可协议
添加滚动侦听器的一种方法是使用
componentDidMount()
生命周期方法。下面的例子应该给你一个想法:当您的 scrollY 位置在 100 及以上时,这会将文本从“向下滚动”更改为“向上滚动”。
编辑:应该避免在每个滚动条上更新状态的矫枉过正。仅在布尔值更改时更新它。