Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,12 @@ If your components share screen scroll container, `document.body` or `document.d
<KeepAlive saveScrollPosition="screen" />
```

If you need to ignore scroll position caching for specific elements, you can use the `saveScrollPositionIgnoreNodeIds` prop to specify a list of element IDs to ignore

```javascript
<KeepAlive saveScrollPositionIgnoreNodeIds={['header', 'sidebar']} />
```

---

## Principle
Expand Down
6 changes: 6 additions & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,12 @@ class App extends Component {
<KeepAlive saveScrollPosition="screen" />
```

如果你需要忽略某些特定元素的滚动位置缓存,可以通过 `saveScrollPositionIgnoreNodeIds` 属性指定要忽略的元素 ID 列表

```javascript
<KeepAlive saveScrollPositionIgnoreNodeIds={['header', 'sidebar']} />
```

---

## 原理概述
Expand Down
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface KeepAliveProps {
autoFreeze?: boolean
wrapperProps?: DivProps
contentProps?: DivProps
saveScrollPositionIgnoreNodeIds?: string[]
[key: string]: any
}

Expand Down
7 changes: 5 additions & 2 deletions src/core/KeepAlive.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ class KeepAlive extends Component {

// DOM 操作将实际内容移出占位元素
eject = (willUnactivate = true) => {
const { id, _helpers } = this.props
const { id, _helpers, saveScrollPositionIgnoreNodeIds } = this.props
const cache = _helpers.getCache(id)
const nodesNeedToSaveScrollPosition = flatten(
flatten([this.props.saveScrollPosition]).map((flag) => {
Expand All @@ -127,7 +127,10 @@ class KeepAlive extends Component {
if (willUnactivate && nodesNeedToSaveScrollPosition.length > 0) {
// 保存该节点下各可滚动元素的滚动位置
cache.revertScrollPos = saveScrollPosition(
nodesNeedToSaveScrollPosition
nodesNeedToSaveScrollPosition,
{
ignoreNodeIds: saveScrollPositionIgnoreNodeIds,
}
)
}

Expand Down
8 changes: 6 additions & 2 deletions src/helpers/saveScrollPosition.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ function getScrollableNodes(from) {
)
}

export default function saveScrollPosition(from) {
const nodes = [...new Set([...flatten(from.map(getScrollableNodes))])]
export default function saveScrollPosition(from, options = {}) {
const { ignoreNodeIds = [] } = options

const nodes = [...new Set([...flatten(from.map(getScrollableNodes))])].filter(
(node) => !ignoreNodeIds.includes(node.id)
)

const saver = nodes.map((node) => [
node,
Expand Down