【问题标题】:Styling the 'root' in MUI v5在 MUI v5 中设置“根”的样式
【发布时间】:2021-10-09 08:27:51
【问题描述】:

例如我正在尝试设置ListItem的样式

我可以找到很多使用 sx 的示例(都使用 Box 作为示例) 但是当我尝试以下类似的方法时,它不起作用

<ListItem button onClick={handleClick}
  sx={{
    root: {
      //
    }
  }}
>

谢谢。

更新

这个尝试也不行

类参考:https://github.com/mui-org/material-ui/blob/v4.9.12/packages/material-ui/src/ListItem/ListItem.js#L29

const MyListItem = styled(ListItem)({
  root: {
    width: "10%",
  },
  button: {
    "&:hover": {
      textDecoration: "none",
      backgroundColor: "blue",
      "@media (hover: none)": {
        backgroundColor: "transparent",
      },
    },
  },
});

  <MyListItem button onClick={handleClick}>
       //content
      </MyListItem>

【问题讨论】:

  • 尝试类而不是 sx
  • 您应该使用 ListItemButton 而不是在 v5 中将属性 button 传递给 ListItem,因为该属性已被弃用。看看他们如何设计ListItemButton here

标签: reactjs material-ui


【解决方案1】:

这是使用sx prop 设置根组件样式的方式

<ListItem
  sx={{
    // your root styles
    "&": {
      // your root styles but with higher CSS specificity
    },
    "&.MuiListItem-root": {
      // your root styles but with even higher CSS specificity
    }
  }}
/>

类似于 v4 中的旧方法:

const useStyles = makeStyles({
  root: {
    // your root styles
    "&": {
      // your root styles but with higher CSS specificity
    },
    "&.MuiListItem-root": {
      // your root styles but with even higher CSS specificity
    }
  }
});
<ListItem className={classes.root}

现场演示

【讨论】:

    猜你喜欢
    • 2022-10-05
    • 2022-01-25
    • 2022-01-13
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-10
    • 2022-07-30
    相关资源
    最近更新 更多