【问题标题】:React-router-dom does not scroll to top of pageReact-router-dom 不滚动到页面顶部
【发布时间】:2022-01-09 18:01:50
【问题描述】:

我快疯了,我正在使用 react-router-dom,当我从页面 A 转到 B 时,我希望它从页面顶部开始,无处不在。我尝试了不同的方法,例如:

componentDidUpdate(){
      console.log('hello');
      document.documentElement.scrollTo(0, 0)
  }

&

componentDidUpdate(){
      console.log('hello');
      window.scrollTo(0, 0)
  }

&

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

function ScrollToTop({ history }) {
   useEffect(() => {
     const unlisten = history.listen(() => {
       window.scrollTo(0, 0);
     });
     return() => {
       unlist();
     }
   }, []);

   return(null);
}

export default withRouter(ScrollToTop);

但不幸的是没有成功,有没有人可以告诉我我能做什么?我正在使用:react": "^16.14.0"

所以我的意图是,如果我点击<Link to={'../shopping cart'}>Shopping cart</Link>,我最终会出现在页面顶部!

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    也许你可以使用 useRef 钩子。像这样:

      const linkRef = useRef(null);
       
           useEffect(() => {
              if (linkRef.current) {
                 linkRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
              }
           }, []);
    
             return <Link ref={linkRef} to='/shopping-card' />
    

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 2021-01-29
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-28
      • 2020-08-08
      相关资源
      最近更新 更多