React/Material UI路由场景下如何设置默认激活的Tab选项卡
问题原因
你当前代码存在3处核心逻辑错误导致无法激活对应Tab:
- Tab的value值和路由对应关系完全颠倒:你定义的
routes[0]是/firsttab,但「First」选项卡的value却绑定了routes[1]也就是/secondtab,和实际路由不匹配 - Tabs组件的value属性逻辑冗余:根路径/已经配置了重定向到
/firsttab,不需要额外设为false - Switch区域的路由路径和你定义的routes数组不匹配:你重定向到的是
/firsttab,但Switch里的路由却是/scutes、/gateways,路径完全不对应,路由匹配也会出错
解决步骤
- 修正Tab和路由的对应关系:「First」选项卡绑定
routes[0],「Second」绑定routes[1] - 简化Tabs的value逻辑:直接取当前路径作为激活值,可额外加兜底逻辑匹配默认路由
- 修正Switch里的路由路径,和你定义的routes数组保持一致
- 修正Route render参数的命名,避免和history对象混淆
修正后完整代码
const routes = ["/firsttab", "/secondtab"]; function MainNavigation() { return ( <div> <IonToolbar> <BrowserRouter> <Route path="/" render={(props) => ( <AppBar> <Tabs className='mat-tab-nav-bar' TabIndicatorProps={{style: {background:'primary'}}} indicatorColor="primary" color="primary" variant="scrollable" scrollButtons="auto" aria-label="scrollable auto tabs" // 直接匹配当前路径,兜底默认激活第一个Tab value={routes.includes(props.location.pathname) ? props.location.pathname : routes[0]} > <Tab className="mat-tab" label="First" value={routes[0]} component={Link} to={routes[0]} /> <Tab className="mat-tab" label="Second" value={routes[1]} component={Link} to={routes[1]} /> </Tabs> </AppBar> )} /> <Switch> <Route path="/secondtab" component={Second}></Route> <Route path="/firsttab" component={First}></Route> <Redirect exact from="/" to="/firsttab" /> </Switch> </BrowserRouter> </IonToolbar> </div> ); } export default MainNavigation;
内容的提问来源于stack exchange,提问作者Devstar34
相关产品推荐
相关产品推荐

