首页 > 解决方案 > Material UI Menu Using Routes 在导航更改时不会滚动到顶部

问题描述

在使用 Material UI 的 MenuItem Link 组件进行导航时,我遇到了滚动问题。

当我导航到不同的组件时,它会保持上次导航的滚动位置。但是,我希望它在导航更改时恢复并从顶部开始。

import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { MenuItem } from '@material-ui/core';
import { Link } from 'react-router-dom'

function TopMenu() {
  return (
    <AppBar>
      <Toolbar>
        <MenuItem component={Link} to='/'>
          <Typography >
            It doesn't scroll to the top when I navigate the the main page. 
          </Typography>
        </MenuItem>
      <Toolbar>
    <AppBar>
  );
}

export default TopMenu;

以下解决方案均不适用于我的情况:

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

在此先感谢您的帮助!

标签: javascriptreactjsmaterial-ui

解决方案


推荐阅读