【问题标题】:Integrates react-route Links into Material UI list将 react-route 链接集成到 Material UI 列表中
【发布时间】:2020-02-23 09:23:30
【问题描述】:

我正在尝试在边栏中创建 list of links。问题是,如果我使用

<ListItem button component='a' href="/persons">

页面会重新加载,而不是像 Link 组件那样转到 url。

<Link to='/persons' >

我想知道,如何将 Material UI listItem href 行为替换为 react-router Link 行为?这是我试图修复的列表:

// this breaks the design
<Link to='/persons' >
    <ListItem button>
        <ListItemIcon>
            <Icon>people</Icon>
        </ListItemIcon>
        <ListItemText primary="Personas" />
    </ListItem>
</Link>

// this reloads the page, i want to avoid
<ListItem button component='a' href="/persons">
    <ListItemIcon>
        <Icon>bar_chart</Icon>
    </ListItemIcon>
    <ListItemText primary="Reports" />
</ListItem>

这是链接的外观:

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您可以使用Link作为ListItem的组件,并如下使用它

    <List>
      <ListItem component={Link} to="/reports">
        <ListItemIcon>
          <Icon>bar_chart</Icon>
        </ListItemIcon>
        <ListItemText primary="Reports" />
      </ListItem>
    </List>
    

    【讨论】:

      【解决方案2】:

      对于 &lt;ListItem /&gt;component 属性可以是 string(对于 dom 元素)或 react component 本身。

      https://material-ui.com/api/list-item/

      你可以定义任何组件

      const ListItemComponent  =  () => {
        return <Link to="/test">Check</Link>
      }
      

      将其作为component 属性传递给&lt;ListItem /&gt;

              <List>
                <ListItem component={ListItemComponent}>
                </ListItem>
              </List>
      

      试试这个? https://stackblitz.com/edit/react-ogpmxx

      【讨论】:

        猜你喜欢
        • 2020-11-18
        • 2021-02-21
        • 2019-07-02
        • 2019-10-17
        • 2018-05-29
        • 1970-01-01
        • 2020-05-16
        • 2019-01-10
        • 2021-04-04
        相关资源
        最近更新 更多