【问题标题】:How to make styles for MUIV5 components?如何为 MUIV5 组件制作样式?
【发布时间】:2022-11-22 21:54:26
【问题描述】:

我在我的项目中使用 Mui v5 组件,目前我正在使用 sx 道具来设置所有 MUI 组件的样式,但是将 sx 放在每个组件的每一行中看起来不太好。所以,我想知道是否有任何其他方法可以像我们在 styled-components 库中那样为每个组件设置样式或应用自定义类。我也知道 MUI 的样式,但它用于制作可重用的组件,但我想使用一些可以帮助我准备可应用于任何组件的样式的东西。

下面是我的代码示例。

  const theme = useTheme();
  return (
    <Box sx={{ border: '1px solid red', flex: 'auto', paddingLeft: '8px' }}>
      <Box
        sx={{
          width: '100%',
          height: '46px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          background: theme.palette['P-10'],
          padding: '8px 24px'
        }}
      >
      </Box>
      <Box sx={{ border: '1px solid green' }}>{AreaChartComp}</Box>
    </Box>
  );
};

If you see there i had to use sx 3 times, which do not want, instead am looking of other way where i can pass classes.

【问题讨论】:

  • 你可以看看MUI styled
  • 是的,我知道我正在使用它来制作可重用组件的样式。我想要 V5 中的 makeStyles 替代品,因为它在 v5 中显示为已弃用

标签: css reactjs material-ui styled-components mui5


【解决方案1】:

您可以像这样在 css 文件中使用 makeStyles:

import { makeStyles } from '@material-ui/core'

export default makeStyles((theme) => ({
    Box: {
         width: '100%',
          height: '46px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          background: theme.palette['P-10'],
          padding: '8px 24px'

    }
    }
    )
    )

并在您的组件中使用它:

    import useStyle from './index.styles'

    const classes = useStyle()

    return (
          <Box className={classes.Box} >
        );
      };

【讨论】:

  • 这是 mui v4,我正在寻找 muiv5 中的解决方案
【解决方案2】:

如果你想将 MUI5 与旧的 makeStyles-approach 一起使用,这样的事情可能会有所帮助:

只需创建一个包含您要使用的样式的对象:

const styles = {
  title: {
    color: 'blue',
  },
  description: {
    color: 'red',
  },
  content: {
    fontStyle: 'italic',
    textDecoration: 'underline',
  },
  button: {
    '&:hover': {
      fontWeight: 'bold',
    },
}
};

然后只需在组件上使用 SX 道具中的每个项目,如下所示:

return (
  <div className="App">
    <Paper>
      <Typography sx={styles.title} variant="h3">Hello World</Typography>
      <Typography sx={styles.description} variant="h5">This is a description</Typography>
      <Typography sx={{...styles.content, color: 'green'}} variant="body1">
        Lorem ipsum dolor sit amet
      </Typography>
      <Button sx={styles.button} variant="contained">The Button</Button>
    </Paper>
  </div>
);

请注意,在第三个示例中,如果您想在 SX 道具中添加一些额外的东西(例如示例中的绿色),您应该使用扩展语法 (...) 扩展样式对象,并注意双卷曲大括号使其成为一个合适的对象。

这个样式对象就像一个普通的 SX 道具一样工作,用于设置子组件、子类或伪类等的样式……如按钮示例所示。

【讨论】:

  • 是的,谢谢 :)
猜你喜欢
  • 2021-10-29
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 2019-11-01
  • 2021-01-09
  • 1970-01-01
  • 2019-10-13
  • 2021-08-16
相关资源
最近更新 更多