【问题标题】:How to get color from palette material ui如何从调色板材质ui中获取颜色
【发布时间】:2021-01-23 13:29:17
【问题描述】:

1)如何从Typography的调色板中获取颜色?
2)如何通过参数从调色板中获取颜色?

代码:-

1)

    <Box color = 'common.white' >
      <Typography color = '(i need common.white from palette like in Box, so how i can get it here )' >
        Some text  
      </Typography>
    </Box>
    <Box color = '(i need gray[arg] from palette what i need write here for use color with arg like gray[500])'>
      Some text
    </Box>

【问题讨论】:

    标签: reactjs colors material-ui themes


    【解决方案1】:

    要从 @material-ui 添加预定义的颜色,从 @material-ui/core/colors 导入该颜色,然后使用 style 属性添加带有参数的颜色。

    import Typography from '@material-ui/core/Typography';
    import { green } from '@material-ui/core/colors';
    
    export default function Color() {
      return (
        <Typography style={{color:green[600]}}>Green color with argument</Typography>
      );
    }
    

    要添加commonprimarysecondary或任何与主题相关的颜色,我们需要使用@material-ui的主题对象。所以有两种方法可以做到这一点:-

    1. 使用useTheme钩子
    import Typography from '@material-ui/core/Typography';
    import {useTheme } from '@material-ui/core';
    
    export default function Color() {
      const theme = useTheme()
    
      return (
        <Typography style={{color:theme.palette.primary.main}}>primary.main</Typography>
      );
    }
    
    1. 使用makeStyles,它在参数本身中提供theme对象,无需单独使用useStyles
    import Typography from '@material-ui/core/Typography';
    import Box from '@material-ui/core/Box';
    import { makeStyles} from '@material-ui/core';
    
    export default function Color() {
      const classes = useStyles()
      return (
        <Box>
          <Typography className={classes.secondaryColorStyle}>secondary Color using makestyles</Typography>
          <Typography className={classes.commonBlack}>common black and white using makestyles</Typography>
        </Box>
      );
    }
    
    const useStyles = makeStyles((theme) => ({
      secondaryColorStyle:{
        color:theme.palette.secondary.main
      },
      commonBlack:{
        color:theme.palette.common.white,
        backgroundColor:theme.palette.common.black
      }
    }));
    

    工作沙盒演示:

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2020-12-24
      • 2021-03-02
      • 2015-07-07
      • 2019-09-26
      相关资源
      最近更新 更多