You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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,路径完全不对应,路由匹配也会出错
解决步骤
  1. 修正Tab和路由的对应关系:「First」选项卡绑定routes[0],「Second」绑定routes[1]
  2. 简化Tabs的value逻辑:直接取当前路径作为激活值,可额外加兜底逻辑匹配默认路由
  3. 修正Switch里的路由路径,和你定义的routes数组保持一致
  4. 修正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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:57:03