我用react路由器实现了material-ui选项卡。当我单击选项卡时,选项卡指示器(该选项卡下方的蓝线)按预期工作,它将移动到按下该选项卡的位置。问题在于,当我重新加载页面时,选项卡指示器会返回到第一个选项卡项目。
我认为这可能是因为选项卡的初始值为零,所以当重新加载页面时,该值再次变为零。
import React, { useState } from 'react';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import SignIn from '../signIn/SignIn'
import SignUp from '../signUp/SignUp';
import About from '../about/About';
import NavbarStyles from './NavbarStyles';
import { Link, Switch, Route } from 'react-router-dom';
import { Paper } from '@material-ui/core';
/**
* This component handles the routing and navigating the user to different sections
*/
export default function Navbar() {
const classes = NavbarStyles();
const [value, setValue] = useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<div className={classes.root}>
<Paper>
<Tabs
value={value}
onChange={handleChange}
variant="scrollable"
scrollButtons="on"
indicatorColor="primary"
textColor="primary"
aria-label="scrollable force tabs example"
>
<Tab label="Sign In" to="/signin" component={Link} />
<Tab label="Sign Up" to="/signup" component={Link} />
<Tab label="About" to="/about" component={Link} />
</Tabs>
</Paper>
<Switch>
<Route component={SignIn} path="/signin" />
<Route component={SignUp} path="/signup" />
<Route component={About} path="/about" />
</Switch>
</div>
);
}
import { makeStyles } from '@material-ui/core/styles';
// This component contains the styles that is being used by its intented component
export default function NavbarStyles() {
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
width: '100%',
backgroundColor: theme.palette.background.paper,
},
}));
return useStyles();
}
答案 0 :(得分:1)
有同样的问题,这是我如何解决的。 由于在刷新页面时Tabs的初始值为0,因此将其重置为home。为防止这种情况,请在handleChange函数的正下方添加一个带有依赖项数组的useEffect。
useEffect(() => {
let path = props.location.pathname;
if (path === "/signin" && value !== 0) setValue(0);
else if (path === "/signup" && value !== 1) setValue(1);
else if (path === "/about" && value !== 2) setValue(2);
}, [value,]);
这会在重新加载页面时设置适当的标签值
答案 1 :(得分:1)
这基于Firealem Erkos代码。在刷新时,我得到0加载,然后高亮条将滑到我当前的那个。.看起来很奇怪..因此,代替usestate(0),我用currentTab代替了0 ...我计算了下面的代码。现在,刷新0时不会短暂突出显示。
const currentTab = () => {
let path = window.location.pathname
if (path === "/Search") return 1
else if (path === "/ZoneInformation") return 2
else if (path === "/Contact") return 3
}
const [value, setValue] = React.useState(**currentTab**);