刷新页面时,Material-UI AppBar按钮跳至屏幕中心

时间:2019-05-21 06:46:02

标签: javascript user-interface material-ui appbar

我有这个Material-UI AppBar:

import React from 'react'
import AppBar from 'material-ui/AppBar'
import AccountCircle from 'material-ui-icons/AccountCircle'
import Toolbar from 'material-ui/Toolbar'
import IconButton from 'material-ui/IconButton'
import HomeIcon from 'material-ui-icons/Home'
import Button from 'material-ui/Button'
import auth from './../auth/auth-helper'
import {Link, withRouter} from 'react-router-dom'

const isActive = (history, path) => {
  if (history.location.pathname == path)
    return {color: '#c61054'}
  else
    return {color: '#ffffff'}

}
const Menu = withRouter(({history}) => (
  <AppBar position="static">
    <Toolbar>
      <Link to="/">
        <IconButton aria-label="Home" style={isActive(history, "/")}>
          <HomeIcon/>
        </IconButton>
      </Link>
      {
        auth.isAuthenticated() && (<span style={{ marginLeft: "auto" }}>
          <Link to="/issues">
            <Button style={isActive(history, "/issues")}>Issues
            </Button>
          </Link>
          <Link to="/users">
            <Button style={isActive(history, "/users")}>Users
            </Button>
          </Link>
          <Link to="/signup">
            <Button style={isActive(history, "/signup")}>Create User
            </Button>
          </Link>
        </span>)
      } 
      {
        !auth.isAuthenticated() && (<span style={{ marginLeft: "auto", marginRight: -12 }}>
          <Link to="/signin">
            <Button style={isActive(history, "/signin")}>Sign In
            </Button>
          </Link>
        </span>)
      }
      {
        auth.isAuthenticated() && (<span  style={{ marginLeft: "auto", marginRight: -12 }}>
          <Link to={"/user/" + auth.isAuthenticated().user._id}>
            <IconButton aria-label="MyProfile" style={isActive(history, "/user/" + auth.isAuthenticated().user._id)}>
              <AccountCircle/>
            </IconButton>
          </Link>
          <Button color="inherit" onClick={() => {
              auth.signout(() => history.push('/'))
            }}>Sign Out</Button>
        </span>)
      }
    </Toolbar>
  </AppBar>
))

export default Menu

注销后,所有内容均按预期显示。 Home图标在左侧,SIGNIN在右侧:

enter image description here

然后我再次登录,一切都如我所愿。 Home图标ISSUESUSERSCREATE USER在左边,Profile图标和SIGNOUT在右边:

enter image description here

如果我随后刷新页面,则ISSUESUSERSCREATE USER会跳到页面中央:

enter image description here

如何阻止这种情况的发生?我是否应该尝试在isActive中添加一些条件来进行设置?也许我可以在函数调用中传递leftright,并根据样式的不同在按钮上设置样式。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

为避免这种定位问题,您可以创建2个span容器,一个包含左侧的选项,另一个包含右侧的选项。然后,您可以将display: flex;justify-content:space-between;设置为其父容器(在本例中为<Toolbar>),这样两个span就会在相反的一侧。您如何看待?

答案 1 :(得分:0)

我认为这是由于使用了“自动”的左边距。您不需要在已验证跨度上留出任何余量:

{
  auth.isAuthenticated() && (<span>
    <Link to="/issues">
      // ...existing code
    </Link>
  </span>)
}

如果您想使用边距将元素向左推,我认为应该是:

margin-right: "auto";