基于滚动React JS的Toggle Class [英] Toggle Class based on scroll React JS
问题描述
我正在使用bootstrap 4导航栏,并想在ig 400px向下滚动后更改背景颜色。我在查看react文档时发现了onScroll,但找不到太多信息。到目前为止,我有...
I'm using bootstrap 4 nav bar and would like to change the background color after ig 400px down scroll down. I was looking at the react docs and found a onScroll but couldn't find that much info on it. So far I have...
我不知道我是否使用了正确的事件侦听器或如何设置高度等。
I don't know if I'm using the right event listener or how to set the height etc.
我并没有真正设置内联样式...
And I'm not really setting inline styles...
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()
生命周期方法。以下示例应该给您一个想法:
One way to add a scroll listener is to use the componentDidMount()
lifecycle method. Following example should give you an idea:
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时,此文本将从向下滚动更改为向上滚动
This changes the Text from "Scroll down" to "Scroll up" when your scrollY position is at 100 and above.
编辑:应避免在每次滚动时更新状态的过大杀伤力。仅在布尔值更改时更新它。
Should avoid the overkill of updating the state on each scroll. Only update it when the boolean value changes.
这篇关于基于滚动React JS的Toggle Class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!