我使用 React Router 实现了 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();
}
最佳答案
这是基于 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**);
关于reactjs - 当我重新加载页面时,Material-UI 选项卡指示器返回到第一个选项卡项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61199980/