You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React滚动显示Div问题:页面加载/刷新时Div无法隐藏求助

问题分析与解决方案

你的问题主要出在初始状态设置错误、页面加载时未执行状态判断,另外componentWillMount已经被React官方废弃,建议换成更规范的写法。下面一步步帮你解决:

核心问题拆解

  1. 你初始化isHide: false,导致页面加载时Div默认显示,和你“滚动后才显示”的需求完全相反;
  2. 页面刚加载时this.prev是undefined,所以window.scrollY < 300 && this.prev这个条件永远不成立,不会触发状态变更;
  3. componentWillMount在React 17及以后版本已被标记为废弃,DOM相关的监听(比如滚动监听)应该放在componentDidMount中执行。

修复后的完整代码

constructor(props){
  super(props);
  // 初始设置为隐藏,符合“滚动后显示”的需求
  this.state={ isHide: true };
  this.hideBar = this.hideBar.bind(this);
  // 初始化prev为当前滚动位置,避免初始判断失效
  this.prev = window.scrollY;
}

hideBar(){
  const { isHide } = this.state;
  const currentScroll = window.scrollY;

  // 简化逻辑:滚动超过300时显示Div,小于300时隐藏(可按需调整)
  if (currentScroll > 300) {
    isHide && this.setState({ isHide: false });
  } else {
    !isHide && this.setState({ isHide: true });
  }

  this.prev = currentScroll;
}

componentDidMount(){
  window.addEventListener('scroll', this.hideBar);
  // 页面加载后立即执行一次,确保初始状态符合当前滚动位置
  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>
  );
}

关键修复点说明

  1. 初始状态调整:把isHide初始值设为true,让Div在页面加载时默认隐藏;
  2. 初始化this.prev:在constructor里就赋值为当前滚动位置,避免初始判断时因undefined导致逻辑失效;
  3. 简化滚动逻辑:把复杂的三元表达式拆成清晰的if-else,后续调整需求更方便;
  4. 页面加载后执行一次判断:确保如果页面加载时已经处于滚动超过300的位置,Div会自动显示;
  5. 修复类名拼接:原来的写法会生成无空格的连写类名(比如newsletterhidenewsletter-container),现在添加空格后类名生效;
  6. 替换生命周期钩子:用componentDidMount替代废弃的componentWillMount,符合React最新规范。

如果你的需求是“滚动到300以内显示,超过300隐藏”,只需要把hideBar里的currentScroll > 300改成currentScroll < 300即可。


内容的提问来源于stack exchange,提问作者Studentofcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:31:18