仅当用户单击返回时,如何将滚动设置为 false?

每当路线发生变化时,我都会使用 Scroll 组件滚动到顶部:


Scroll.js


import { useEffect } from 'react';

import { withRouter } from 'react-router-dom';


function ScrollToTop({ history }) {

  useEffect(() => {

    const unlisten = history.listen(() => {

      window.scrollTo(0, 0);

    });

    return () => {

      unlisten();

    }

  }, []);


  return (null);

}


export default withRouter(ScrollToTop);

<Router>

  <Fragment>

    <ScrollToTop />

    <Switch>

        <Route path="/" exact component={Home} />

    </Switch>

  </Fragment>

</Router>

我想要实现的是,每当用户在浏览器上单击返回时,滚动到顶部应该不起作用。


每当用户在浏览器中单击返回时,如何将滚动到顶部设置为 false?


拉丁的传说
浏览 49回答 1
1回答

慕容708150

你不能检查你的历史动作,如果它是 POP,就忽略滚动?就像是function ScrollToTop({ history }) {&nbsp;&nbsp;&nbsp; useEffect(() => {&nbsp; &nbsp; const unlisten = history.listen(() => {&nbsp; &nbsp; &nbsp; if (history.action !== 'POP') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.scrollTo(0, 0);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return () => {&nbsp; &nbsp; &nbsp; unlisten();&nbsp; &nbsp; }&nbsp; }, []);&nbsp; return (null);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript