【问题标题】:ReactJS component going behind NavbarReactJS 组件落后于 Navbar
【发布时间】:2020-04-23 07:40:31
【问题描述】:

在我的 React 应用程序中,顶部有一个导航栏。我在 App.js 中调用了这个 Navbar 组件,如下所示。

export default function App() {
   return (
      <Router>
         <Fragment>
            <Navbar />
            <Route exact path="/" component={Home} />
            <section>
               <Switch>
                  <Route exact path="/login" component={Login} />
                  <PrivateRoute exact path="/dashboard" component={Dashboard} />
               </Switch>
            </section>
         </Fragment>
      </Router>
   );
}

问题是,每当我点击这些 URL 中的任何一个,例如“/login”、“/dashboard”,与它们关联的组件都会呈现在导航栏的后面而不是在它的下方。虽然我可以在&lt;Navbar /&gt;下方添加多个&lt;br/&gt;标签来将这些组件移到下面,但这似乎不是一个好的解决方案,因为某些组件上面已经有很大的空白,添加&lt;br/&gt;会将它们进一步移动到下面我不想要。如何解决这个问题?我的其他组件返回简单的&lt;div&gt;。我的导航栏是来自 ma​​terial-ui/core 库的 &lt;Appbar position='fixed'&gt;

【问题讨论】:

  • 尝试为您的NavBar 组件添加样式。必须是display: "flex"; flex: 1;

标签: javascript reactjs react-router material-ui


【解决方案1】:

Material UI 官方文档详细介绍了这个特定问题:https://material-ui.com/components/app-bar/#fixed-placement

如果您在 Material UI AppBar 上使用 Fixed Placement,则需要通过在应用栏下方添加第二个空的 &lt;Toolbar /&gt; 组件或使用 theme.mixins.toolbar CSS 来偏移您的内容。


使用第二个 &lt;Toolbar /&gt; 组件的解决方案 A:

function App() {
  return (
    <React.Fragment>
      <AppBar position="fixed">
        <Toolbar>{/* content */}</Toolbar>
      </AppBar>
      <Toolbar />
    </React.Fragment>
  );
}

使用theme.mixins.toolbar的解决方案B:

const useStyles = makeStyles(theme => ({
  offset: theme.mixins.toolbar,
}))

function App() {
  const classes = useStyles();
  return (
    <React.Fragment>
      <AppBar position="fixed">
        <Toolbar>{/* content */}</Toolbar>
      </AppBar>
      <div className={classes.offset} />
    </React.Fragment>
  )
};

MUI 还建议使用position="sticky" 来避免此问题;但是 IE11 不支持此功能,因此请谨慎使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-15
    • 2021-04-09
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多