【问题标题】:How to update style of a React element with className如何使用 className 更新 React 元素的样式
【发布时间】:2018-05-09 20:34:46
【问题描述】:

所以我在我的 create react 应用程序中使用了 Ant Design UI 库,这让我很难编辑更复杂的 Ant Design 组件的样式。就像进度条默认是蓝色的:

我想让它变成另一种颜色,当我在 Chrome 控制台中查看 HTML 时,我看到:

该元素的classNameant-progress-bg。有什么办法可以在我的 React 组件中编写一些代码并将样式更新为从 style={width: "12.5%, height: 8}style={color: 'red', width: "12.5%, height: 8}

这是我使用 ant 设计库生成进度条所需编写的所有 React 代码:

import { Progress } from 'antd';

<Progress
    percent={percentVotes}
    showInfo={false}
    status="active"
/>

我也尝试过导入 CSS 并添加了一个带有我想要的样式的“ant-progress-bg”CSS 类,但它没有做任何事情。

在我的Matches.css 文件中,我有:

.ant-progress-bg {
    color: red;
}

我使用import './Matches.css'; 将其导入到我的Matches.js 文件中

【问题讨论】:

  • 你能分享你的反应代码产生进度标签吗?如果您的反应代码中隐藏了“ant-progress-bg”,那么您将必须导入 css 并添加一个“ant-progress-bg”css 类,并使用您想要的样式。
  • 我尝试导入 CSS 并添加了一个带有我想要的样式的“ant-progress-bg”CSS 类,但它没有做任何事情。
  • 文档涵盖了这种特殊情况。 ant.design/components/progress
  • @KevinB 谢谢,但我以red 为例。我实际上需要颜色才能更改为任何颜色。

标签: javascript css reactjs getelementsbyclassname


【解决方案1】:

这是一个演示https://codesandbox.io/s/k0m0nl1my3

如果你想改变所有地方的进度条颜色然后覆盖这个类

.ant-progress-bg {
  background-color: red !important;
}

如果您只想更改此特定进度条的颜色,请添加一些额外的类,例如

.my-progress-bar .ant-progress-bg {
  background-color: red !important;
}

如果您将less 用于自定义样式,那就更简单了

.my-progress-bar {
  .ant-progress-bg {
    background-color: red !important;
  }
}   

<Progress
  percent={percentVotes}
  showInfo={false}
  status="active"
  className="my-progress-bar"
/>

【讨论】:

  • @QLiu 然后你需要添加!important。我更新了答案
  • @QLiu 我在这里创建了一个演示,它正在运行codesandbox.io/s/k0m0nl1my3
  • 如果你仍然有问题,我猜你已经以错误的顺序导入了样式文件。在 Ant Design css 之后导入您的自定义样式
  • @QLiu 欢迎.. 很高兴为您提供帮助
猜你喜欢
  • 2016-11-26
  • 2016-02-09
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
相关资源
最近更新 更多