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

React中跳转页面返回后恢复SearchListWrapper滚动位置的问题

解决React中div滚动位置在页面返回时恢复的问题

核心思路

通过sessionStorage存储目标div的滚动位置,在组件挂载时读取并设置该值,同时在滚动过程中实时更新存储内容。

具体实现步骤

1. 组件挂载时恢复滚动位置

在类组件的componentDidMount生命周期中,读取sessionStorage里保存的滚动值,设置给SearchListWrapper元素:

componentDidMount() {
  const savedPosition = sessionStorage.getItem("scrollPosition");
  if (savedPosition && this.myRef.current) {
    // 用requestAnimationFrame确保DOM渲染完成后再设置,避免无效赋值
    requestAnimationFrame(() => {
      this.myRef.current.scrollTop = parseInt(savedPosition, 10);
    });
  }
}

2. 优化滚动存储逻辑(可选)

如果滚动事件触发频繁,可添加防抖函数减少sessionStorage的写入次数,降低性能损耗:

// 定义防抖工具函数
debounce(func, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}

// 在构造函数中绑定防抖后的方法
constructor(props) {
  super(props);
  this.myRef = React.createRef();
  this.handleScrollPosition = this.debounce(this.handleScrollPosition.bind(this), 100);
}

// 原滚动处理方法保持逻辑不变
handleScrollPosition(e){
  if (this.myRef.current) {
    sessionStorage.setItem("scrollPosition", this.myRef.current.scrollTop.toString());
  }
};

3. 可选:清理存储值

如果不需要在其他页面保留该滚动位置,可在组件卸载时清除存储:

componentWillUnmount() {
  sessionStorage.removeItem("scrollPosition");
}

完整代码示例

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.handleScrollPosition = this.debounce(this.handleScrollPosition.bind(this), 100);
  }

  debounce(func, delay) {
    let timer;
    return (...args) => {
      clearTimeout(timer);
      timer = setTimeout(() => func.apply(this, args), delay);
    };
  }

  componentDidMount() {
    const savedPosition = sessionStorage.getItem("scrollPosition");
    if (savedPosition && this.myRef.current) {
      requestAnimationFrame(() => {
        this.myRef.current.scrollTop = parseInt(savedPosition, 10);
      });
    }
  }

  handleScrollPosition(e){
    if (this.myRef.current) {
      sessionStorage.setItem("scrollPosition", this.myRef.current.scrollTop.toString());
    }
  };

  onClickResult() {
    // 你的页面跳转逻辑,比如路由跳转或新页面打开
  }

  render() {
    return (
      <SearchListWrapper className="TestSL" ref={this.myRef} onScroll={this.handleScrollPosition}>
        <StyledLink onClick={() => { this.onClickResult(); }}>
          {/* 链接内容 */}
        </StyledLink>
        {/* 列表内容 */}
      </SearchListWrapper>
    );
  }
}

注意事项

  • 确保SearchListWrapper元素设置了overflow: auto或overflow: scroll样式,否则不会生成滚动条,scrollTop值始终为0。
  • sessionStorage是会话级存储,关闭浏览器后会自动清除;若需要持久化保存,可改用localStorage,但注意及时清理过期数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:20:26