【问题标题】:is it possible to use material ui tabs and still use react router?是否可以使用材料 ui 选项卡并仍然使用反应路由器?
【发布时间】:2020-03-07 17:29:10
【问题描述】:

我已从Tabs component in material ui, 自定义代码

  <AppBar position="static">
    <Tabs
      variant="fullWidth"
      value={value}
      onChange={handleChange}
      aria-label="nav tabs example"
    >
      <LinkTab label="Page One" href="/drafts" {...a11yProps(0)} />
      <LinkTab label="Page Two" href="/trash" {...a11yProps(1)} />

    </Tabs>
  </AppBar>
  <TabPanel value={value} index={0}>
    Page Onee
  </TabPanel>
  <TabPanel value={value} index={1}>
    Page Two
  </TabPanel>

基本上是两个选项卡,单击一个,它会显示文本“Page Onee”,单击另一个选项卡,会显示文本“Page Two”。

但是,我希望能够使用反应路由器,以便我可以将一个组件带到每个选项卡并分配路由。在反应路由器中它会是这样的(我知道反应路由器还有更多的事情要做,但在标签代码中就是这样):

<Link class="nav-link" to="/component1">Click here to see component1</Link>

<Link class="nav-link" to="/component2">Click here to see component2</Link>

但是在我展示给你的第一段代码(我从材料 ui 自定义的那个)中,我有那些 &lt;TabPanel&gt; 标签。

有没有简单的方法把 react 路由器扔进去?

如果不能包含 React 路由器,我如何仍然能够使用该材料 ui 代码渲染我的组件?

【问题讨论】:

    标签: javascript reactjs react-router material-ui jsx


    【解决方案1】:

    如果您遇到与 Kislay Kunal 相同的问题,请尝试以下链接:Material-UI's Tabs integration with react router 4?

    要点是,除非您将浏览器状态绑定到您的材质 UI 选项卡状态,否则选项卡将更改 url 路径,但指定路径不会将您导航到正确的选项卡。所以基本上只是以 Mickael Muller 的例子,将value 替换为this.props.history.location.path 就像这样

    <AppBar position="static">
     <Tabs
      variant="fullWidth"
      value={this.props.history.location.path}
      onChange={handleChange}
      aria-label="nav tabs example"
     >
       <Tab component={Link} label="Page One" to="/drafts" {...a11yProps(0)} />
       <Tab component={Link} label="Page Two" to="/trash" {...a11yProps(1)} />
    
     </Tabs>
    </AppBar>
    <TabPanel value={this.props.history.location.path} index={0}>
     Page Onee
    </TabPanel>
    <TabPanel value={this.props.history.location.path} index={1}>
     Page Two
    </TabPanel>
    

    【讨论】:

      【解决方案2】:

      尝试将material-ui的Tab组件与toprops和component={Link}props一起使用。不要忘记import { Link } from 'react-router-dom';

      <AppBar position="static">
       <Tabs
        variant="fullWidth"
        value={value}
        onChange={handleChange}
        aria-label="nav tabs example"
       >
         <Tab component={Link} label="Page One" to="/drafts" {...a11yProps(0)} />
         <Tab component={Link} label="Page Two" to="/trash" {...a11yProps(1)} />
      
       </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
       Page Onee
      </TabPanel>
      <TabPanel value={value} index={1}>
       Page Two
      </TabPanel>
      

      对我来说很好用

      【讨论】:

      • 嘿,我正在使用相同的方法,但问题是,说我输入 localhost/trash 它并没有直接将我作为普通链接带到那里。有没有办法强制这种行为。
      • @KislayKunal 将您的标签面板包裹在一个带有 子节点的 中,每个子节点都有一个反映您的标签路由的路径。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2020-11-29
      • 2020-11-30
      • 2021-01-04
      相关资源
      最近更新 更多