Skip to content

Conversation

@fightZy
Copy link

@fightZy fightZy commented Jul 11, 2025

背景与需求

在使用 react-activation 进行组件状态保持时,saveScrollPosition 功能会自动保存和恢复页面中所有可滚动元素的滚动位置。哪怕滚动元素在KeepAlive包裹之外,但在某些业务场景中,我们需要对特定的元素进行例外处理,比如:

  1. 固定导航栏或侧边栏:这些元素的滚动位置不应该被保存,因为它们在不同页面间应该保持初始状态
  2. 动态内容区域:某些滚动容器的内容可能会动态变化,保存滚动位置可能导致用户体验问题

解决方案

新增 saveScrollPositionIgnoreNodeIds 属性,允许指定要忽略滚动位置缓存的元素ID列表。

主要修改内容

1. 类型定义更新 (index.d.ts)

export interface KeepAliveProps {
  // ... 其他属性
  saveScrollPositionIgnoreNodeIds?: string[]
}

2. 核心逻辑修改 (src/core/KeepAlive.js)

  • eject 方法中接收新的 saveScrollPositionIgnoreNodeIds 属性
  • 将该参数传递给 saveScrollPosition 函数

3. 滚动位置保存函数增强 (src/helpers/saveScrollPosition.js)

  • 新增 options 参数支持,包含 ignoreNodeIds 配置
  • 在获取可滚动节点时过滤掉指定ID的元素

4. 文档更新 (README.md & README_CN.md)

  • 添加新参数的使用说明和示例代码

使用示例

// 忽略元素id为'header', 'sidebar'的置顶导航栏和侧边栏的滚动位置缓存
<KeepAlive saveScrollPositionIgnoreNodeIds={['header', 'sidebar']}>
  <YourComponent />
</KeepAlive>

@youngBrain1893
Copy link

#355 感觉我的问题和这个一样的

@fightZy
Copy link
Author

fightZy commented Oct 4, 2025

#355 感觉我的问题和这个一样的

是的,现在默认会缓存所有滚动

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants