Javascript 如何在react中切换滚动事件上的类?
如果页面在react中滚动,我需要添加或删除元素上的类。我编写了这样一个代码来跟踪页面滚动:Javascript 如何在react中切换滚动事件上的类?,javascript,reactjs,Javascript,Reactjs,如果页面在react中滚动,我需要添加或删除元素上的类。我编写了这样一个代码来跟踪页面滚动: export default class TestComponenet extends React.Component { constructor(props) { super(props); autoBind(this); this.state = { scrolled: false } } componentDidMount() {
export default class TestComponenet extends React.Component {
constructor(props) {
super(props);
autoBind(this);
this.state = {
scrolled: false
}
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
};
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
};
handleScroll(event) {
this.setState({srolled: true});
};
render() {
return (
<div className ={scrolled ? 'scrolling' : ''}></div>
);
}
}
导出默认类TestComponenet扩展React.Component{
建造师(道具){
超级(道具);
自动绑定(本);
此.state={
滚动:false
}
}
componentDidMount(){
window.addEventListener('scroll',this.handleScroll);
};
组件将卸载(){
window.removeEventListener('scroll',this.handleScroll);
};
handleScroll(活动){
this.setState({srolled:true});
};
render(){
返回(
);
}
}
但我只能跟踪滚动,但不能动态切换类。浏览器中没有真正的“滚动状态”。当用户滚动时,您会得到一个事件,然后它就结束了。如果用户有一段时间没有滚动,您可以保留一个超时,将其设置为不滚动:
示例
class App extends React.Component {
state = {
scrolled: false
};
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
handleScroll = event => {
this.setState({ scrolled: true });
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.setState({ scrolled: false });
}, 200);
};
render() {
const { scrolled } = this.state;
return (
<div
className={scrolled ? "scrolling" : ""}
style={{
width: 200,
height: 1000,
backgroundColor: scrolled ? "blue" : "red"
}}
/>
);
}
}
类应用程序扩展了React.Component{
状态={
滚动:false
};
componentDidMount(){
window.addEventListener(“滚动”,this.handleScroll);
}
组件将卸载(){
window.removeEventListener(“滚动”,this.handleScroll);
}
handleScroll=事件=>{
this.setState({scrolled:true});
clearTimeout(this.timer);
this.timer=setTimeout(()=>{
this.setState({滚动:false});
}, 200);
};
render(){
const{scrolled}=this.state;
返回(
);
}
}
你的问题很模糊。您认为您可以详细说明一下,也可以显示您的整个组件吗?添加了…………this.state.scrolled