[英]ReactJS component going behind Navbar
In my React app, I have a navigation bar on top.在我的 React 应用程序中,顶部有一个导航栏。 I call this Navbar component in App.js as shown below.我在 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>
);
}
The problem is that, whenever I hit any of these URLs like '/login', '/dashboard', The component associated with them renders behind the navbar and not below it.问题是,每当我点击这些 URL 中的任何一个,例如“/login”、“/dashboard”,与它们关联的组件呈现在导航栏后面而不是在导航栏下方。 While I can add multiple <br/>
tags below <Navbar />
to shift these components below, but this does not seem like a good solution as some components already have significant whitespace above them and adding <br/>
will shift them even further below which I don't want.虽然我可以在<Navbar />
下方添加多个<br/>
标签来将这些组件移动到下方,但这似乎不是一个好的解决方案,因为某些组件上方已经有大量空白,添加<br/>
将进一步移动它们低于我不想要的。 How to solve this issue?如何解决这个问题? My other components return simple <div>
.我的其他组件返回简单的<div>
。 My Navbar is a <Appbar position='fixed'>
from the material-ui/core library.我的<Appbar position='fixed'>
是来自material-ui/core库的<Appbar position='fixed'>
。
The official Material UI documentation covers this specific issue in detail: https://material-ui.com/components/app-bar/#fixed-placement官方 Material UI 文档详细介绍了这个特定问题: https : //material-ui.com/components/app-bar/#fixed-placement
If you use Fixed Placement on a Material UI AppBar you will need to offset your content by either including a second empty <Toolbar />
component below the appbar or by using theme.mixins.toolbar
CSS.如果您在 Material UI AppBar 上使用 Fixed Placement,您将需要通过在 appbar 下方包含第二个空<Toolbar />
组件或使用theme.mixins.toolbar
CSS 来偏移您的内容。
Solution A using a second <Toolbar />
component:使用第二个<Toolbar />
组件的解决方案 A:
function App() {
return (
<React.Fragment>
<AppBar position="fixed">
<Toolbar>{/* content */}</Toolbar>
</AppBar>
<Toolbar />
</React.Fragment>
);
}
Solution B using theme.mixins.toolbar
:解决方案 B 使用theme.mixins.toolbar
:
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 also suggests using position="sticky"
instead to avoid this issue; MUI 还建议使用position="sticky"
来避免这个问题; however this is not supported in IE11 so use with caution.但是,IE11 不支持此功能,因此请谨慎使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.