我正在使用bootstrap 4导航栏,并想在ig
400px向下滚动后更改背景颜色。我在查看react文档时发现了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;
添加滚动侦听器的componentDidMount()
一种方法是使用生命周期方法。以下示例应给您一个想法:
import React from 'react';
import { render } from 'react-dom';
class App extends React.Component {
state = {
isTop: true,
};
componentDidMount() {
document.addEventListener('scroll', () => {
const isTop = window.scrollY < 100;
if (isTop !== this.state.isTop) {
this.setState({ isTop })
}
});
}
render() {
return (
<div style={{ height: '200vh' }}>
<h2 style={{ position: 'fixed', top: 0 }}>Scroll {this.state.isTop ? 'down' : 'up'}!</h2>
</div>
);
}
}
render(<App />, document.getElementById('root'));
当您的scrollY位置在100或更高位置时,这会将文本从“向下滚动”更改为“向上滚动”。
编辑:应避免过分更新每个滚动条上的状态。仅在布尔值更改时更新它。