【问题标题】:Setting default active tab in React/ Material ui routing在 React/Material ui 路由中设置默认活动选项卡
【发布时间】:2021-11-26 04:08:08
【问题描述】:

我在我的 react 应用程序中使用 Material Ui 选项卡进行路由。我可以设置默认 url(这样 '/' url 将重定向到 '/firsttab' 路由,但即使路由正确,这也不会使 'First' 选项卡显示为活动状态。我该如何做到这一点? 谢谢!

const routes = ["/firsttab", "/secondtab"];
function MainNavigation() {
  return (
    <div >
   <IonToolbar >
      <BrowserRouter >
        <Route
          path="/"
          render={(history) => (
            <AppBar>
              <Tabs 
              className='mat-tab-nav-bar'
              TabIndicatorProps={{style: {background:'primary'}}}
              indicatorColor="primary"
              color="primary"
              variant="scrollable"
              scrollButtons="auto"
              aria-label="scrollable auto tabs"
              value={history.location.pathname !== "/" ? history.location.pathname : false}
                  >
                <Tab className="mat-tab"
                  label="First"
                  value={routes[1]}
                  component={Link}
                  to={routes[1]}
                ></Tab>
                <Tab className="mat-tab "
                  label="Second"
                  value={routes[0]}
                  component={Link}
                  to={routes[0]}
                ></Tab>
              </Tabs>
            </AppBar>
          )}
        ></Route>
       
        <Switch >
          <Route path="/scutes" component={Second}></Route>
          <Route path="/gateways" component={First}></Route>
          <Redirect exact from="/" to="/firsttab" /> <- this is the initial route redirect
        </Switch>
      </BrowserRouter>
      </IonToolbar>
    </div>

  );
}

export default MainNavigation;

【问题讨论】:

    标签: reactjs routes react-hooks material-ui


    【解决方案1】:

    您可以创建一个函数来根据窗口位置检索选项卡索引,如下所示:

    const getIndex = (location) => {
        const index = routes.findIndex(function (item, index) {
            if (item === location) return true;
        })
        return index
    }
    

    那么你可以这样称呼它:

    value={history.location.pathname !== "/" ? getIndex(history.location.pathname) : false}
    

    注意,如果路径名为“/”时返回false,则不会选择选项卡

    你会以这样的方式结束:

    function MainNavigation() {
    
        const getIndex = (location) => {
            const index = routes.findIndex(function (item, index) {
                if (item === location) return true;
            })
            return index
        }
    
        return (
            ...
            <Tabs
            ...
            value={history.location.pathname !== "/" ? getIndex(history.location.pathname) : false}
            >
            ...
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-24
      • 2019-05-17
      • 1970-01-01
      • 2022-10-13
      • 2017-01-25
      • 2017-01-09
      • 1970-01-01
      • 2018-05-26
      相关资源
      最近更新 更多