简体   繁体   English

React & MUI:无法使用 makeStyles 设置 MUI 图标样式

[英]React & MUI: Unable to style MUI Icon with makeStyles

I want to style mui Icons using className attribute, however it doesn't work.我想使用className属性设置 mui 图标的样式,但是它不起作用。 But when I'm applying inline styles it works as expected.但是当我应用内联 styles 时,它按预期工作。 I will have a few Icons in the component which I want to style the same way that's why I don't want to use inline styles and copy the same code several times.我将在组件中有一些图标,我想以相同的方式设置样式,这就是为什么我不想使用内联 styles 并多次复制相同的代码。 What am I doing wrong?我究竟做错了什么? Can someone please help?有人可以帮忙吗?

import React from 'react';
import FacebookIcon from '@mui/icons-material/Facebook';
import TwitterIcon from '@mui/icons-material/Twitter';
import { makeStyles } from '@mui/styles';

const useStyles = makeStyles({
    root: {
        fontSize: '50px',
        margin: '10px',
        color: 'primary'
    }
});

const Links = () => {

    const classes = useStyles();

    return(
        <div>
            //this doesn't work
            <TwitterIcon className={classes.root} />

            //this works
            <FacebookIcon sx= {{ fontSize:'50px', margin:'10px', color:'primary' }} />  
        </div>
    );
}

export default Links;

Thank you谢谢

makeStyles is legacy API that relies on JSS, not emotion. makeStyles是依赖 JSS而不是情感的遗留 API。 It should not be used unless you are supporting older versions of Mui.除非您支持旧版本的 Mui,否则不应使用它。

The recommended way is to either use styled or specify variants in the theme object.推荐的方法是在theme object 中使用styled或指定变体。

import { styled } from '@mui/material'

const SocialMediaIcon = styled(Icon)(({ theme }) => ({
  fontSize: 50,
  margin: 10,
  color: theme.palette.text.primary,
}))

<SocialMediaIcon component={TwitterIcon} />
const theme = createTheme({
  components: {
    MuiIcon: {
      variants: [
        {
          props: { variant: 'social' },
          style: {
            fontSize: 50,
            margin: 10,
            color: 'primary',
          },
        },
      ],
    },
  },
})

<Icon variant="social" component={Instagram} />

Demo. 演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM