【问题标题】:Creating styles from Material-UI theme that can be reused across components?从 Material-UI 主题创建可以跨组件重用的样式?
【发布时间】:2019-06-11 05:25:53
【问题描述】:

在 Material-UI 4 中,可以轻松创建可在组件内部使用的样式。我为此使用了makeStyles() 函数。

const useStyles = makeStyles((theme: Theme) => ({
    hoverableContent: {
        color: theme.palette.primary.contrastText,
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
            backgroundColor: theme.palette.primary.dark
        }
    }
}));

const MyComponent = () => {
    const classes = useStyles();
    ...
}

但是,我想在多个组件中重用这种样式。在 Material-Ui 4 中执行此操作的最佳方法是什么?

注意:我认为这是一个更高级别的抽象:共享抽象类(以受控方式)而不只是颜色(在主题中)。

【问题讨论】:

    标签: material-ui


    【解决方案1】:

    您可以执行以下操作之一:

    1. 在组件之间共享样式
    const styles = (theme: Theme) => ({
        hoverableContent: {
            color: theme.palette.primary.contrastText,
            backgroundColor: theme.palette.primary.main,
            '&:hover': {
                backgroundColor: theme.palette.primary.dark
            }
        }
    })
    

    这种方法会导致这个问题。你如何合并多种风格? https://github.com/mui-org/material-ui/issues/11517

    1. 生成一个全局类名并将其应用到有意义的地方。但要小心类名冲突和摇树

    【讨论】:

      【解决方案2】:

      我知道这有点晚了,但我只是面对它并通过制作一个钩子来解决:

      // someSharedClasses.ts
      export default makeStyles((theme)=>createStyles({
          hoverableContent: {
              color: theme.palette.primary.contrastText,
              backgroundColor: theme.palette.primary.main,
              '&:hover': {
                  backgroundColor: theme.palette.primary.dark
              }
          }
      }));
      

      和其他组件:

      import useSharedClasses from './someSharedClasses.ts';
      const MyComponent = () => {
        const sharedClasses = useSharedClasses();
        // use sharedClasses.hoverableContent as className
      }
      

      【讨论】:

        猜你喜欢
        • 2020-05-08
        • 2021-07-17
        • 2019-12-30
        • 2020-05-07
        • 2019-11-28
        • 1970-01-01
        • 2020-01-24
        • 1970-01-01
        • 2021-05-23
        相关资源
        最近更新 更多