[英]Changing MUI Chip primary or secondary color
我试图以编程方式更改 MUI Chip
的颜色,但运气不佳。 根据Chip
API,您必须通过 color 属性使用枚举中的三个值之一设置颜色; 默认、主要和次要。 然后您应该能够覆盖colorPrimary
或colorSecondary
css 类,并且背景颜色应该改变。
这是我的代码示例:
<Chip key={label.id} color='primary' classes={{ colorPrimary: label.color }} label={label.label} />
以及浏览器中元素的图片: https: //i.imgur.com/bWYGzzz.png 还不能内联 :(
如果您查看所选元素,您将看到我尝试应用的正确颜色 #ff0000,因此它正在获取颜色并将其放在某处。
我已经尝试过这种变体,添加了 colorBackground 属性,但是我收到一条错误消息,指出 colorPrimary 类需要一个字符串而不是一个对象
<Chip key={label.id} color='primary' classes={{ colorPrimary: { backgroundColor: label.color } }} label={label.label} />
再次重申我的目标:我想对芯片应用十六进制代码颜色以更改背景颜色。
我试图以编程方式更改Material-ui芯片的颜色,但运气不佳。 根据Chip Api,您必须通过color prop使用枚举中的三个值之一来设置颜色。 默认,主要和次要。 然后,您应该能够覆盖colorPrimary或colorSecondary css类,并且背景色也应更改。
这是我的代码示例:
<Chip key={label.id} color='primary' classes={{ colorPrimary: label.color }} label={label.label} />
以及浏览器中元素的图片: https: //i.imgur.com/bWYGzzz.png尚不能内联:(
如果您查看选定的元素,您将看到我尝试应用的正确颜色#ff0000,因此它可以获取颜色并将其放置在某处。
我尝试了这种变体,添加了colorBackground属性,但是收到一条错误消息,说colorPrimary类期望使用字符串而不是对象
<Chip key={label.id} color='primary' classes={{ colorPrimary: { backgroundColor: label.color } }} label={label.label} />
再次重申我的目标:我想将十六进制代码颜色应用于芯片以更改背景颜色。
任何信息都是有帮助的,谢谢!
对于那些试图在 v5 之前获得它的人(需要向调色板添加新颜色),一个简单的包装器将完成工作:
import React from 'react';
import PropTypes from 'prop-types';
import MaterialChip from '@material-ui/core/Chip';
import { withStyles } from '@material-ui/core/styles';
const Chip = (props) => {
const StyledChip = withStyles({
root: {
'color': 'white',
'backgroundColor': `${props.color} !important`,
'&:hover': {
backgroundColor: props.color,
filter: 'brightness(120%)',
},
'&:active': {
boxShadow: 'none',
backgroundColor: props.color,
borderColor: props.color,
},
},
outlined: {
color: props.color,
border: `1px solid ${props.color}`,
backgroundColor: `transparent !important`,
},
icon: {
color: props.variant === 'outlined' ? props.color : 'white',
},
deleteIcon: {
color: props.variant === 'outlined' ? props.color : 'white',
},
})(MaterialChip);
return <StyledChip {...props} />;
};
Chip.propTypes = {
color: PropTypes.string,
variant: PropTypes.oneOf(['regular, outlined']),
};
export default Chip;
您可以使用createTheme
轻松设置Chip
组件的primary
或secondary
颜色:
const theme = createTheme({
components: {
MuiChip: {
styleOverrides: {
colorPrimary: {
backgroundColor: 'red',
},
colorSecondary: {
backgroundColor: 'brown',
},
},
},
},
});
<Chip label="primary" color="primary" />
<Chip label="secondary" color="secondary" />
或者,如果您使用的是MUI v5 ,您可以在sx
道具的帮助下快速更改其颜色:
<Chip label="sx" sx={{ bgcolor: 'green', color: 'white' }} />
如果您希望能够通过道具指定不同的颜色,您可以使用styled
:
const options = {
shouldForwardProp: (prop) => prop !== 'bgcolor',
};
const StyledChip = styled(
Chip,
options,
)(({ bgcolor }) => ({
color: 'white',
backgroundColor: bgcolor,
}));
<StyledChip label="styled" bgcolor="purple" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.