【问题标题】:React / Material-UI: Use variable reference in custom themeReact / Material-UI:在自定义主题中使用变量引用
【发布时间】:2021-11-16 09:10:02
【问题描述】:

Material-UI (React) 中是否有办法在自定义主题中使用对同一主题中定义的变量的引用?例如,组件MuiBottomNavigation 应该使用原色(主)作为背景。

import { createTheme, useTheme } from '@mui/material/styles';

const theme = createTheme({
    palette: {
        primary: {
            main: '#f6b1b2'
        }
    },
    components: {
        MuiBottomNavigation: {
            styleOverrides: {
                root: {
                    // This is not working
                    backgroundColor: {palette.primary.main}
                },
            }
        }
    }
});

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您可以通过创建多个主题然后将它们合并为一个来实现此目的:

    // Define all your default styles
    const themeBase = createTheme({
      palette: {
        primary: {
          main: "#f6b1b2"
        }
      }
    });
    
    // Define all your component styles
    const themeComponents = createTheme({
      components: {
        MuiBottomNavigation: {
          styleOverrides: {
            root: {
              backgroundColor: themeBase.palette.primary.main
            },
          }
        }
      }
    });
    
    const theme = createTheme({
      ...themeBase,
      components: themeComponents.components,
    });
    

    当然,您不需要为组件创建额外的主题。您也可以将它们插入最后的theme

    【讨论】:

      【解决方案2】:

      不,你不能。定义主题时没有这样的 API 可以访问主题。所以这样的事情是行不通的

      styleOverrides: {
        root: {
          backgroundColor: theme => theme.palette.primary.main
        },
      }
      

      要解决此问题,您可以将常用共享值放入变量中并引用它:

      const primaryMain = '#f6b1b2';
      
      const theme = createTheme({
        palette: {
          primary: {
            main: primaryMain,
          }
        },
        components: {
          MuiBottomNavigation: {
            styleOverrides: {
              root: {
                backgroundColor: primaryMain,
              }
            }
          }
        }
      });
      

      如果你只需要访问一个默认的主题变量,你可以创建一个并像这样引用它:

      const defaultTheme = createTheme();
      
      const theme = createTheme({
        components: {
          MuiBottomNavigation: {
            styleOverrides: {
              root: {
                backgroundColor: defaultTheme.palette.primary.main,
              }
            }
          }
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2020-04-09
        • 2021-11-14
        • 1970-01-01
        • 2019-05-24
        • 1970-01-01
        • 1970-01-01
        • 2020-07-05
        • 2020-08-19
        • 1970-01-01
        相关资源
        最近更新 更多