diff --git a/README.md b/README.md index 0d5ea13..ba0cd03 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,12 @@ If your components share screen scroll container, `document.body` or `document.d ``` +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 + +``` + --- ## Principle diff --git a/README_CN.md b/README_CN.md index ae46b07..3e35eb8 100644 --- a/README_CN.md +++ b/README_CN.md @@ -373,6 +373,12 @@ class App extends Component { ``` +如果你需要忽略某些特定元素的滚动位置缓存,可以通过 `saveScrollPositionIgnoreNodeIds` 属性指定要忽略的元素 ID 列表 + +```javascript + +``` + --- ## 原理概述 diff --git a/index.d.ts b/index.d.ts index ce064ae..e746be1 100644 --- a/index.d.ts +++ b/index.d.ts @@ -20,6 +20,7 @@ export interface KeepAliveProps { autoFreeze?: boolean wrapperProps?: DivProps contentProps?: DivProps + saveScrollPositionIgnoreNodeIds?: string[] [key: string]: any } diff --git a/src/core/KeepAlive.js b/src/core/KeepAlive.js index 2ba76a4..7bbd0b9 100644 --- a/src/core/KeepAlive.js +++ b/src/core/KeepAlive.js @@ -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) => { @@ -127,7 +127,10 @@ class KeepAlive extends Component { if (willUnactivate && nodesNeedToSaveScrollPosition.length > 0) { // 保存该节点下各可滚动元素的滚动位置 cache.revertScrollPos = saveScrollPosition( - nodesNeedToSaveScrollPosition + nodesNeedToSaveScrollPosition, + { + ignoreNodeIds: saveScrollPositionIgnoreNodeIds, + } ) } diff --git a/src/helpers/saveScrollPosition.js b/src/helpers/saveScrollPosition.js index 26c6c26..78d9bbd 100644 --- a/src/helpers/saveScrollPosition.js +++ b/src/helpers/saveScrollPosition.js @@ -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,