Javascript reactJS中的setTimeout和clearTimeout
我正在尝试创建一个在显示主要内容之前淡出的问候UI。可以找到想要的效果 当达到某个滚动输入时,例如从顶部开始的100pxJavascript reactJS中的setTimeout和clearTimeout,javascript,reactjs,Javascript,Reactjs,我正在尝试创建一个在显示主要内容之前淡出的问候UI。可以找到想要的效果 当达到某个滚动输入时,例如从顶部开始的100px 问候语出现5秒钟后消失 主要内容等待问候语淡出并显示出来 我用setTimeout实现了这个效果,但我现在想知道如何正确设置clearTimeout 这是我的密码 componentDidMount() { window.addEventListener( "wheel", () => requestAnimationFrame(this
componentDidMount() {
window.addEventListener(
"wheel",
() => requestAnimationFrame(this.handleScroll.bind(this)),
false
);
}
handleScroll(e){
const scrolltop = window.scrollY;
scrolltop > 120 ? this.showGreeting().bind(this):null
}
showGreeting(){
this.setState({
greetingDisplay:true,
})
const timer = setTimeout(this.showContent.bind(this),5000);
}
showContent(){
this.setState({
greetingDisplay:false,
contentDisplay:1,
})
//How do I clear the timer here?
}
- 这是我的尝试,代码笔
showGreeting
中,您正在设置超时并将其存储在local const
varibale中。而不是将其绑定到组件实例,即this
constructor(){
this.timer = null;
//............rest
}
showGreeting(){
this.setState({
greetingDisplay:true,
})
this.timer=setTimeout(this.showContent.bind(this),3000);
^^^^^^^^^^^
}
调用showContent
时,将更新状态,该状态将触发render
,然后触发componentdiddupdate
生命周期
在组件diddupdate
中,使用this.timer
清除超时
componentDidUpdate{
clearTimeout(this.timer);
}
您可以轻松使用ES6 arrow功能,而不会产生以下副作用:
showContent = () => {
this.setState({
greetingDisplay:false,
contentDisplay:1,
});
}
showGreeting = () => {
this.setState({
greetingDisplay:true,
});
setTimeout( () => this.showContent, 3000 );
}