64

目前我正在使用以下代码使用 jss 为元素添加颜色。

const styleSheet = theme => ({
  root: {
     backgroundColor: theme.colors.red,
  },
})

我想知道是否存在基于颜色添加不透明度的功能theme.colors.red

示例 smt 像: backgroundColor: color(theme.colors.red, .05),

4

8 回答 8

141

Material UI 有一个colorManipulator 实用文件,其中包含一个alpha函数:

import { alpha } from '@material-ui/core/styles/colorManipulator';

/**
 * Sets the absolute transparency of a color.
 * Any existing alpha values are overwritten.
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
 * @param {number} value - value to set the alpha channel to in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

{
    backgroundColor: alpha(theme.colors.red, 0.5)
}

或者,您可以从 npm 添加颜色库以进行颜色操作:

import Color from 'color';

{
    backgroundColor: Color(theme.colors.red).alpha(0.5).string()
}
于 2018-08-23T05:57:28.403 回答
15

或者,您可以使用 Material UI Next 中提供的淡入淡出功能。

import {fade} from 'material-ui/styles/colorManipulator';

const theme = createMuiTheme({
  overrides: {
    MuiButton: {
      root: {
        boxShadow: `0 4px 8px 0 ${fade(defaultTheme.palette.primary[500], 0.18)}`,
      }
    },
  }
});

export default theme;

这是它的工作原理:https ://github.com/mui-org/material-ui/blob/v1-beta/src/styles/colorManipulator.js#L157-L164

另一种解决方案可能是使用来自https://github.com/styled-components/poliished的类似颜色函数

于 2018-01-02T15:51:46.007 回答
10

假设您还没有在颜色中定义 alpha 通道,您还可以执行以下操作:

backgroundColor: theme.colors.red + '00' 

这会将 Alpha 通道设置为 0,因此是透明的。'00'您可以在之间附加任何值'ff'

于 2019-04-17T20:02:42.113 回答
4

I found a solution using

 backgroundColor: theme.utils.rgba(theme.axColor.black, 0.7),
于 2017-11-13T16:38:09.347 回答
3

您可以使用 RGBA 值

const styleSheet = theme => ({
  root: {
     backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
})

https://facebook.github.io/react-native/docs/colors.html

于 2017-11-13T16:18:34.517 回答
2

其中一些答案引用了已弃用的 Material-UI 函数。当前的首选方法是使用alpha

import { alpha } from "@material-ui/core";

...
                 // yields rgba(255,255,255,0.85)
backgroundColor: alpha(theme.palette.background.paper, 0.85) 
于 2021-07-22T15:35:32.653 回答
1

另一种可能是:

import color from "color"

const themeColorsRed = color
  .rgb(theme.colors.red)
  .array()

然后你可以这样做:

{
  backgroundColor: `rgba(${themeColorsRed}, 0.05)`,
}
于 2021-01-07T00:06:09.087 回答
0

值得一提的是,8 位十六进制代码也可以使用

const styleSheet = theme => ({
  root: {
     backgroundColor: '#ffffff80',
  },
})
于 2018-11-23T18:45:06.387 回答