React-Static 在页面更改时滚动到顶部

React-Static scroll to top on page change

有没有办法在使用 react-static 更改页面时滚动到顶部?我正在使用 @reach/router,它默认包含在 react-static.

我已经试过了:

<Router onChange={window.scrollTo(0,0)}>
   <Routes path="*"/>
</Router>

ans 这个(来自这个 issue

<Router history={history} autoScrollToTop={true}>
   <Routes path="*"/>
</Router>

但两者均无效。

react-static 文档中提到了最后一个解决方案,但似乎已弃用,因为它不再出现在文档中。

尝试让一个组件为您处理滚动并位于您的应用程序组件之上。

用法:

import ManageScroll from './ManageScroll';
ReactDOM.render(<Fragment><ManageScroll/><App/></Fragment>, node);

ManageScroll.js:

import React from "react";
import { Location } from "@reach/router";

let scrollPositions = {};

class ManageScrollImpl extends React.Component {
  componentDidMount() {
    try {
      // session storage will throw for a few reasons
      // - user settings
      // - in-cognito/private browsing
      // - who knows...
      let storage = JSON.parse(sessionStorage.getItem("scrollPositions"));
      if (storage) {
        scrollPositions = JSON.parse(storage) || {};
        let { key } = this.props.location;
        if (scrollPositions[key]) {
          window.scrollTo(0, scrollPositions[key]);
        }
      }
    } catch (e) {}

    window.addEventListener("scroll", this.listener);
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.listener);
  }

  componentDidUpdate() {
    const { key } = this.props.location;
    if (!scrollPositions[key]) {
      // never seen this location before
      window.scrollTo(0, 0);
    } else {
      // seen it
      window.scrollTo(0, scrollPositions[key]);
    }
  }

  listener = () => {
    scrollPositions[this.props.location.key] = window.scrollY;
    try {
      sessionStorage.setItem(
        "scrollPositions",
        JSON.stringify(scrollPositions)
      );
    } catch (e) {}
  };

  render() {
    return null;
  }
}

export default () => (
  <Location>
    {({ location }) => <ManageScrollImpl location={location} />}
  </Location>
);

查看此要点以获取更多信息https://gist.github.com/ryanflorence/39a37a85254159fd7a5ca54027e175dc

希望对您有所帮助!

您需要创建一个新组件Scrolltotop.js

import { useEffect } from 'react'
import { useLocation } from '@reach/router'

export default function Scrolltotop () {
  const { pathname } = useLocation()

  useEffect(() => {
    window.scrollTo(0, 0)
  }, [pathname])

  return null
}

并将其导入到 App.js

import Scrolltotop from './components/Scrolltotop'

并将其添加到App函数中:

function App () {
  return (
    <Root>
      <Scrolltotop/>
      <Router>
        <Routes path="*"/>
      </Router>
    </Root>
  )
}