首页 > 解决方案 > 更改 MUI 芯片原色或副色

问题描述

我正在尝试以编程方式更改 MUI 的颜色,Chip但运气不佳。根据ChipAPI,您必须通过 color 属性使用枚举中的三个值之一设置颜色;默认,主要和次要。然后您应该能够覆盖colorPrimaryor colorSecondarycss 类并且背景颜色应该改变。

这是我的代码示例:

<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} />

再次重申我的目标:我想将十六进制代码颜色应用于芯片以更改背景颜色。

标签: reactjsmaterial-ui

解决方案


你可以通过多种方式做到这一点。

可以直接添加样式

<Chip key={label.id} color='primary' style={{backgroundColor:'green'}} label={label.label} />

或者您可以覆盖该类:

const StyleChip = withStyles({
  root: {
    backgroundColor:'salmon'
  }
})(Chip);

在任何地方使用,您只会替换ChipStyleChip

<StyleChip key={label.id} color='primary' label={label.label} />

但是如果你想通过编程来上色,第一种方法是完美的,因为

style={{backgroundColor:_thisCanBeVariable_}}


推荐阅读