React Router v4 - 切换组件时保持滚动位置

IT技术 javascript reactjs scrollview react-router-v4 react-router-dom
2021-05-14 01:37:43

<Route>用 react-router 创建了两个s。

  • /cards -> 纸牌游戏列表
  • /cards/1 -> 纸牌游戏的细节 #1

当用户单击“返回列表”时,我想将用户滚动到他在列表中的位置。

我怎样才能做到这一点?

4个回答

代码沙盒的工作示例

React Router v4 不提供对滚动恢复的开箱即用支持,而且就目前而言,它们也不会。React Router V4 - Scroll Restoration of their docs 部分中,您可以阅读更多相关信息。

因此,每个开发人员都可以编写逻辑来支持这一点,尽管我们确实有一些工具可以实现这一点。

element.scrollIntoView()

.scrollIntoView()可以在一个元素上调用,你可以猜到,它会将它滚动到视图中。支持很好,目前97%的浏览器都支持。来源:icanuse

所述<Link />组件可以通过对状态

React Router 的 Link 组件有一个toprop,你可以提供一个对象而不是字符串。这就是这个样子。

<Link to={{ pathname: '/card', state: 9 }}>Card nine</Link>

我们可以使用 state 将信息传递给将要呈现的组件。在这个例子中, state 被分配了一个数字,它足以回答你的问题,稍后你会看到,但它可以是任何东西。路由/card渲染<Card />现在可以访问props.location.state 中的变量 state ,我们可以随意使用它。

标记每个列表项

在渲染各种卡片时,我们为每张卡片添加一个独特的类。这样我们就有了一个标识符,我们可以传递它并知道当我们导航回卡片列表概览时需要将此项目滚动到视图中。

解决方案

  1. <Cards /> 呈现一个列表,每个项目都有一个唯一的类;
  2. 当一个项目被点击时,Link />将唯一标识符传递给<Card />;
  3. <Card /> 呈现卡片详细信息和具有唯一标识符的后退按钮;
  4. 单击按钮并<Cards />安装后,.scrollIntoView()将使用来自 的数据滚动到先前单击的项目props.location.state

下面是各个部分的一些代码片段。

// Cards component displaying the list of available cards.
// Link's to prop is passed an object where state is set to the unique id.
class Cards extends React.Component {
  componentDidMount() {
    const item = document.querySelector(
      ".restore-" + this.props.location.state
    );
    if (item) {
      item.scrollIntoView();
    }
  }

  render() {
    const cardKeys = Object.keys(cardData);
    return (
      <ul className="scroll-list">
        {cardKeys.map(id => {
          return (
            <Link
              to={{ pathname: `/cards/${id}`, state: id }}
              className={`card-wrapper restore-${id}`}
            >
              {cardData[id].name}
            </Link>
          );
        })}
      </ul>
    );
  }
}

// Card compoment. Link compoment passes state back to cards compoment
const Card = props => {
  const { id } = props.match.params;
  return (
    <div className="card-details">
      <h2>{cardData[id].name}</h2>
      <img alt={cardData[id].name} src={cardData[id].image} />
      <p>
        {cardData[id].description}&nbsp;<a href={cardData[id].url}>More...</a>
      </p>
      <Link
        to={{
          pathname: "/cards",
          state: props.location.state
        }}
      >
        <button>Return to list</button>
      </Link>
    </div>
  );
};

// App router compoment.
function App() {
  return (
    <div className="App">
      <Router>
        <div>
          <Route exact path="/cards" component={Cards} />
          <Route path="/cards/:id" component={Card} />
        </div>
      </Router>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

由于没有关于如何在功能组件中执行此操作的答案,这里是我为一个项目实现的钩子解决方案:

import React from 'react';
import { useHistory } from 'react-router-dom';

function useScrollMemory(): void {
  const history = useHistory<{ scroll: number } | undefined>();

  React.useEffect(() => {
    const { push, replace } = history;

    // Override the history PUSH method to automatically set scroll state.
    history.push = (path: string) => {
      push(path, { scroll: window.scrollY });
    };
    // Override the history REPLACE method to automatically set scroll state.
    history.replace = (path: string) => {
      replace(path, { scroll: window.scrollY });
    };

    // Listen for location changes and set the scroll position accordingly.
    const unregister = history.listen((location, action) => {
      window.scrollTo(0, action !== 'POP' ? 0 : location.state?.scroll ?? 0);
    });

    // Unregister listener when component unmounts.
    return () => {
      unregister();
    };
  }, [history]);
}

function App(): JSX.Element {
  useScrollMemory();

  return <div>My app</div>;
}

使用此覆盖解决方案,您无需担心在所有Link元素中传递状态一个改进是使其通用,因此它向后兼容pushreplace方法,history但在我的特定情况下这不是必需的,所以我省略了它。

我正在使用,react-router-dom但您可以轻松地覆盖 vanilla historyAPI 的方法。

另一种可能的解决方案是将您的/cards/:id路线呈现为全屏模式并将/cards路线安装在其后面

对于使用 Redux 的完整实现,您可以在CodeSandbox上看到这一点

我通过使用历史 API 来做到这一点。

  1. 路线更改后保存滚动位置。

  2. 当用户单击后退按钮时恢复滚动位置。

将滚动位置保存在 中getSnapshotBeforeUpdate在 中恢复componentDidUpdate

  // Saving scroll position.
  getSnapshotBeforeUpdate(prevProps) {
    const {
      history: { action },
      location: { pathname }
    } = prevProps;

    if (action !== "POP") {
      scrollData = { ...scrollData, [pathname]: window.pageYOffset };
    }

    return null;
  }

  // Restore scroll position.
  componentDidUpdate() {
    const {
      history: { action },
      location: { pathname }
    } = this.props;

    if (action === "POP") {
      if (scrollData[pathname]) {
        setTimeout(() =>
          window.scrollTo({
            left: 0,
            top: scrollData[pathname],
            behavior: "smooth"
          })
        );
      } else {
        setTimeout(window.scrollTo({ left: 0, top: 0 }));
      }
    } else {
      setTimeout(window.scrollTo({ left: 0, top: 0 }));
    }
  }