How do people handle scroll restoration with react-router v4?

前端 未结 5 432
一整个雨季
一整个雨季 2020-12-28 17:30

I\'m experiencing some problems with scroll positions on the back button (history popstate) when using react-router. React router v4 doesn\'t handle scroll management out of

5条回答
  •  情书的邮戳
    2020-12-28 18:00

    Note that history.scrollRestoration is just a way of disabling the browser's automatic attempts at scroll restoration, which mostly don't work for single-page apps, so that they don't interfere with whatever the app wants to do. In addition to switching to manual scroll restoration, you need some sort of library that provides integration between the browser's history API, React's rendering, and the scroll position of the window and any scrollable block elements.

    After not being able to find such a scroll restoration library for React Router 4, I created one called react-scroll-manager. It supports scrolling to top on navigation to a new location (aka history push) and scroll restoration on back/forward (aka history pop). In addition to scrolling the window, it can scroll any nested element that you wrap in an ElementScroller component. It also supports delayed/asynchronous rendering by using a MutationObserver to watch the window/element content up to a user-specified time limit. This delayed rendering support applies to scroll restoration as well as scrolling to a specific element using a hash link.

    npm install react-scroll-manager

    import React from 'react';
    import { Router } from 'react-router-dom';
    import { ScrollManager, WindowScroller, ElementScroller } from 'react-scroll-manager';
    import { createBrowserHistory as createHistory } from 'history';
    
    class App extends React.Component {
      constructor() {
        super();
        this.history = createHistory();
      }
      render() {
        return (
          
            
              
                
                  
    ...
    ...
    ); } }

    Note that an HTML5 browser (10+ for IE) and React 16 are required. HTML5 provides the history API, and the library uses the modern Context and Ref APIs from React 16.

提交回复
热议问题