[英]How to fix Show div on scroll (React)
After i set some div to show after scroll, the result is the div is not hidden when the page is open(or reload) 在我将某些div设置为滚动显示后,结果是打开页面(或重新加载)时div未隐藏
I have tried to have the - componentWillMount, and - componentDidMount for the lifecycle, but i got the same result 我试图在生命周期中使用-componentWillMount和-componentDidMount,但结果却相同
This is the code 这是代码
constructor(props){
super(props);
this.state={
isHide:false,
};
this.hideBar = this.hideBar.bind(this)
}
hideBar(){
let {isHide} = this.state;
window.scrollY < 300 && this.prev ?
!isHide && this.setState({isHide:true})
:
isHide && this.setState({isHide:false})
this.prev = window.scrollY;
}
componentWillMount(){
window.addEventListener('scroll',this.hideBar);
}
componentWillUnmount(){
window.removeEventListener('scroll',this.hideBar);
}
render() {
let classHide=this.state.isHide?"newsletterhide":""
return (
<div className={classHide+"newsletter-container"}>
<div className="newsletter-details">
<h3 style={{margin:0, fontSize:"0.9em"}}>
Get latest updates in web technologies
</h3>
<p className="p-newsletter">
I write articles related to web technologies, such as design trends, development tools, UI/UX case studies and reviews, and more. Sign up to my newsletter to get them all.
</p>
</div>
<div className="newsletter-form">
<input
name="email"
type="email"
placeholder="Email address"
className="newsletter-input"
/>
<button className="newsletter-button">
Count me in!
</button>
</div>
</div>
);
}
Thanks for your help!, hope the other who need it find it useful. 感谢您的帮助!希望其他需要它的人对它有所帮助。
As I understood, you want to show subscribe to newsletter box when user scrolls down in the page. 据我了解,当用户在页面中向下滚动时,您想显示“ 订阅时事通讯”框。 Why don't you just write:
你为什么不写:
hideBar() {
this.setState({
isHidden: window.scrollY < 300
});
}
And setting isHidden
to true
at the beginning should solve your problem. 在一开始将
isHidden
设置为true
应该可以解决您的问题。 If not, then call hideBar
method at componentDidMount
. 如果不是,则在
componentDidMount
处调用hideBar
方法。
And also, I recommend that you show the newsletter box after user spend some time looking at the website; 另外,我建议您在用户花一些时间浏览网站后显示新闻简报框; eg show it 15 seconds after he/she reads the article.
例如,在他/她阅读文章后15秒钟将其显示出来。
Assuming the problem is during reloads there being a page offset and your intension is to show the div then, 假设问题是在重新加载期间存在页面偏移,并且您的意图是显示div,
componentDidMount() {
if(window.pageYOffset) this.setState({ isHide: false, });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.