我正在使用material-ui react选项卡以及Router链接,并且除了active选项卡之外,其他所有功能都正常运行。尽管单击时会显示内容,但在用户单击了两次标签后,将选择活动标签。
似乎将值重新初始化为初始值,然后在第二次单击中更新。
任何帮助将不胜感激。
const classes = useStyles();
const [value, setValue] = useState(4);
const [anchorEl, setAnchorEl] = useState(null);
const [open, setOpen] = useState(false);
const handleChange = (event, newValue) => {
setValue(newValue);
}
return (
<div className={classes.root}>
<AppBar position="static">
<Paper>
<Tabs
value={value}
variant="standard"
indicatorColor="primary"
textColor="primary"
selectionFollowsFocus="true"
onChange={handleChange}
centered>
<Tab component={Link}
to="/balances"
icon={<AccountBalance />}
label="..."/>
<Tab component={Link}
to="/finalisations"
icon={<LabelImportant />}
label="..." />
<Tab component={Link}
to="/publications"
icon={<Public />}
label="..." />
<Tab component={Link}
to="/models"
icon={<FormatAlignCenter />}
label="ΥΠΟΔΕΙΓΜΑΤΑ" />
<Tab component={Link}
to="/accounts"
icon={<AccountBox />}
label="..." />
<Tab component={Link}
to="/users"
icon={<People />}
label="..."/>
</Tabs>
答案 0 :(得分:0)
您可以尝试以下方法:
import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
import { makeStyles } from '@material-ui/core/styles'
import { AppBar, Tab, Tabs } from '@material-ui/core'
import {
Apps,
Event,
Equalizer,
ShoppingBasket,
} from '@material-ui/icons'
function a11yProps(index) {
return {
id: `scrollable-force-tab-${index}`,
'aria-controls': `scrollable-force-tabpanel-${index}`,
}
}
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
width: '100%',
backgroundColor: theme.palette.background.paper,
},
tabs: {
display: 'flex',
justifyContent: 'center',
},
}))
const NavBarItem = {
'/schedule': 0,
'/reports': 1,
'/utils': 2,
'/sale-management': 3,
}
const NavBar = ({ location, history }) => {
const classes = useStyles()
const [value, setValue] = React.useState(NavBarItem[location.pathname])
const handleChange = (newValue, event) => {
setValue(newValue)
}
const navigateTo = pathname => {
history.push(pathname)
handleChange(NavBarItem[pathname])
}
return (
<div className={classes.root}>
<AppBar position='static' color='primary'>
<Tabs
value={value}
onChange={handleChange}
className={classes.tabs}
variant='scrollable'
scrollButtons='on'
indicatorColor='secondary'
textColor='inherit'
aria-label='scrollable force tabs example'
>
<Tab
label='...'
icon={<Event />}
{...a11yProps(0)}
onClick={() => navigateTo('/schedule')}
/>
<Tab
label='...'
icon={<Equalizer />}
{...a11yProps(1)}
onClick={() => navigateTo('/reports')}
/>
<Tab
label='...'
icon={<Apps />}
{...a11yProps(2)}
onClick={() => navigateTo('/utils')}
/>
<Tab
label='...'
icon={<ShoppingBasket />}
{...a11yProps(3)}
onClick={() => navigateTo('/sale-management')}
/>
</Tabs>
</AppBar>
</div>
)
}
export default withRouter(NavBar)