0

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

我已经尝试过这个:

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

ans this (from this issue )

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

但两者都没有工作。

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

4

2 回答 2

3

You need to create a new component 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
}

and import it to App.js

import Scrolltotop from './components/Scrolltotop'

and add it to the App function :

function App () {
  return (
    <Root>
      <Scrolltotop/>
      <Router>
        <Routes path="*"/>
      </Router>
    </Root>
  )
}
于 2020-04-25T14:56:53.547 回答
0

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

用法:

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

希望这可以帮助!

于 2020-04-24T14:54:20.200 回答