【问题标题】:MUI Change ListItemText styles when active in react-router在 react-router 中活动时 MUI 更改 ListItemText 样式
【发布时间】:2020-10-29 08:57:34
【问题描述】:

我目前正在使用来自 MUI 的 ListItem。我试图在它处于活动状态时使其更大胆,但似乎 font-weight 不起作用。

代码见下文。

<List
      component='nav'
      aria-label='main mailbox folders'
    >
      <ListItem
        button
        component={NavLink}
        exact
        to='/accounts'
        activeClassName={classes.active}
        className={classes.appBarNavButtons}
      >
        <MyAccountsIcon />
        <ListItemText
          style={{ marginLeft: '20px', fontSize: 'large' }}
          primary='My Accounts'
        />
      </ListItem>
</List>

风格:

appBarNavButtons: {
  color: colors.blueGrey[800],
  textTransform: 'none',
  letterSpacing: 0,
},
active: {
  color: '#0056b3',
  fontWeight: 'bolder',
  '& $icon': {
    color: theme.palette.primary.main,
  }
}

任何帮助或建议将不胜感激。

【问题讨论】:

    标签: css reactjs material-ui


    【解决方案1】:

    V5

    在 v5 中,ListItemmakeStylesbutton 属性已弃用。替代方案是 ListItemButtonstyled,如下例所示:

    import MuiListItemButton from '@mui/material/ListItemButton';
    import ListItemText from '@mui/material/ListItemText';
    import { styled } from '@mui/material/styles';
    
    const ListItemButton = styled(MuiListItemButton)({
      '&.active .MuiTypography-root': {
        fontWeight: 'bold',
      },
    });
    
    <ListItem disablePadding>
      <ListItemButton component={NavLink} exact to="/">
        <ListItemText primary="Home" />
      </ListItemButton>
    </ListItem>
    

    V4

    您的样式的优先级低于ListItem 中来自Typography 的样式,您可以使用嵌套选择器覆盖它以增加CSS 特异性:

    const useStyles = makeStyles({
      active: {
        '& .MuiTypography-root': {
          fontWeight: 'bold',
        },
      },
    });
    
    <ListItem
      button
      component={NavLink}
      exact
      to="/"
      activeClassName={classes.active}
    >
      <ListItemText primary="Home" />
    </ListItem>
    

    【讨论】:

    • 嗨,@NearHuscarl,非常感谢您的帮助。不幸的是,它仍然没有使文本更粗。我将尝试添加 .active 并查看它是否有效。再次感谢!
    • @Ohhimarccc 我已经更新了我的答案。我使用了错误的 CSS 选择器。对不起。
    • 嘿@NearHuscarl,它有效!非常感谢您的大力帮助!
    猜你喜欢
    • 2021-05-20
    • 2017-10-14
    • 2022-07-22
    • 2020-06-30
    • 1970-01-01
    • 2017-06-22
    • 2019-12-02
    • 2022-11-12
    • 1970-01-01
    相关资源
    最近更新 更多