簡體   English   中英

使用帶有反應路由器的材料ui選項卡?

[英]Using material ui tabs with react router?

我在反應/打字稿中有一個項目。 我有一個看起來像這樣的反應路由器

 const Root = () => ( <> <NavBar/> <Router> <Route path="/" component={Home} /> <Route path="/timer" component={TimerPage} /> </Router> </> );

我有一個看起來像這樣的 material-ui appbar

 export default function NavBar() { return ( <div> <AppBar position="static"> <Tabs> <Tab label="Timer" to="/timer" component={TimerPage} /> </Tabs> </AppBar> </div> ); }

有幾個問題 - 首先 Tab 中的“to”無法編譯。 其次,考慮到它們做的事情非常相似,我如何讓這兩個組件一起工作?

如果您嘗試導航到另一個頁面,請包裝您的選項卡組件,讓 react-router 處理導航並使用 react-router 歷史記錄進行導航,

 <Tabs value={value} onChange={handleChange} aria-label="simple tabs 
     example">
   <div onClick={() => history.push("/timer")}>
        <Tab   label="Timer" />
    </div>
  </Tabs>
<Router>
        <Route path="/" component={Home} />
        <Route path="/timer" component={TimerPage} />
</Router>

Route應該在Switch里面。 此外,如果您寫path="/"這意味着您將訪問的任何頁面仍將 go 到“主頁”頁面。 這是因為 react-router 做了類似“最少”的路線檢查。 因此,如果您在"/images/1"之前定義了路徑"/images" ,兩者都會將您路由到"/images" 相反,您可以更改這些路徑的順序,或者在第一個之前添加exact關鍵字。

看看下面的例子。

<Router>
    <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/timer" component={TimerPage} />
    </Switch>
</Router>

或者

<Router>
    <Switch>
        <Route path="/timer" component={TimerPage} />
        <Route path="/" component={Home} />
    </Switch>
</Router>

至於您的第二個問題,您應該將AppBar (或div或任何容器)放入Router並將Link分配給Tabcomponent屬性:

<Router>
    <AppBar position="static">
          <Tabs>
              <Tab label="Timer" to="/timer" component={Link}  />
          </Tabs>
    </AppBar>
</Router>

請記住, Link組件是從 react-router 導入的,而不是從 @mui 導入的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM