【问题标题】:Issue trying to override mui theme in Reactjs尝试在 Reactjs 中覆盖 mui 主题的问题
【发布时间】:2021-12-12 19:03:18
【问题描述】:

我有一个带有一些列表项的导航栏,我想在选择 MuiListItemButton 时覆盖 MuiListItemText 的样式。我可以覆盖突出显示,但不能使用文本或图标来实现。我可以覆盖 ListItemText 但所有这些,我只想覆盖“已选择”(Mui-selected)。 我正在使用 Mui 5.2.0。 这是我的方法。

const Theme = createTheme({
    components: {        
         MuiListItemButton: {
            styleOverrides: {
              root: {
                borderRadius: '4px',
                padding: '12px',
                '&.Mui-selected': {
                  backgroundColor: '#F2F2EA',

                  MuiListItemText: {
                    styleOverrides: {
                      secondary: {
                        color: 'red',
                             ...

【问题讨论】:

  • 您使用什么版本的 Material-UI 以及您如何覆盖您的方法的主题?
  • 梅5.2.0。我已经用一些信息更新了帖子,我正在使用 createTheme 和 ThemeProvider

标签: reactjs material-ui


【解决方案1】:

您应该以相同的深度定义覆盖主题结构。

const Theme = createTheme({
    components: {        
         MuiListItemButton: {
            styleOverrides: {
              root: {...}
            }
         },
         // it should be another component, not a nested structure
         MuiListItemText: {
            styleOverrides: {
              secondary: {
                ...

您可以使用 sx prop、styled-components 或 makeStyles API 自定义单个组件。

https://mui.com/customization/how-to-customize/

这是一个使用样式组件的示例。

const CustomListItemButton = styled(ListItemButton)(() => ({
  borderRadius: '4px',
  padding: '12px',
  '&.Mui-selected': {
    backgroundColor: '#F2F2EA',
    ...
}));

【讨论】:

  • 我目前正在尝试,我可以覆盖它,但是所有的 ItemListsTexts,我只想在选择 MuiListItemButton 时更改样式(我可以在按钮中使用 '&. Mui-selected'。所以我只需要在选择父项时覆盖样式。我该怎么做?
  • @Mr_Lahey,已更新。
【解决方案2】:

试试这个:

import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';

【讨论】:

  • 是的,我已将其导入并将主题传递给 ThemeProvider。正如我所说,MuiListItemButton 已被覆盖,因此 ThemeProvider 正在工作
【解决方案3】:

我认为这不是最好的方法,但我可以通过以下方式做到这一点:

<ListItemText
  secondary={
    <Typography
      variant="body2"
      style={selected === '/' ? { color: 'red' } : { color 'green' }>
        Item Text</Typography> } />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-24
    • 2022-07-21
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2011-01-23
    • 2023-01-28
    相关资源
    最近更新 更多