【问题标题】:How to change background color of active radio button in react-bootstrap?如何更改 react-bootstrap 中活动单选按钮的背景颜色?
【发布时间】:2021-06-11 19:45:18
【问题描述】:

在一个 React 项目中,我使用单选按钮列出日历日期和日期。我的意图是更改这些单选按钮的背景颜色并保留它。单击屏幕时它不应消失。

以下为参考代码:

{newDate.map((data, i) => (
          <ButtonGroup toggle style={{ width: "100%" }}>
            <GridListTile style={gridListStylePhoto}>
              <h5>{currday(data.getDay())}</h5>
              <ToggleButton
                key={i}
                type="radio"
                active="true"
                variant="light"
                name="radio"
                value={currday(data.getDay()) + " " + data.getDate()}
                checked={radioValue === data.getDate()}
                onChange={(e) => {
                  handleChange(e);
                }}
              >
                <br />
                {data.getDate()}
              </ToggleButton>
            </GridListTile>
          </ButtonGroup>
        ))}

以下是样式参考:

input[type="checkbox"],
input[type="radio"] {
  display: none;
}
.btn-light {
  background-color: transparent;
  border: transparent;
}

.btn-light:checked {
  background-color: red // Here is color doesn't change
}

为了改变上述单选按钮的背景颜色可以做些什么?

请参考下面的 Codesandbox 链接。

代码沙盒链接:https://codesandbox.io/s/material-demo-forked-hcbxl

【问题讨论】:

  • 您的问题没有提及有关单击/选择电台的任何内容。请更新它
  • 好的,那么最好的解决方案是什么?
  • 1.请edit 并使用您在 cmets 中提供的信息更新问题,例如“我的意思是当单选按钮在选择时处于活动状态” 2. 您的demo.js 有很多样板代码。请参阅minimal reproducible example。当您更新问题时,它会在活动源中遇到问题

标签: css reactjs


【解决方案1】:

您可以使用现有的 onChange 事件切换每个单选按钮的类。

const handleChange = (e) => {
    const newData = e.target.value;
    var elems = document.querySelectorAll(".toggleButtonNew.active");
    [].forEach.call(elems, function (el) {
      el.classList.remove("active");
    });
    e.target.closest("label").classList.toggle("active");
    setRadioValue(newData);
};

并将您想要的样式添加到该类

.active {
    background-color: red !important;
}

【讨论】:

  • 它没有改变。你能参考上面提到的codeandbox链接吗
  • 请立即查看。
  • 哇几乎完成了,但是当点击其他没有被取消选中的人时
  • 非常好的逻辑,但是,由于其他人也被选中,所以没有完成......感觉就像复选框,而那些是单选按钮
  • 你太棒了......这足以说明......非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
  • 2015-01-03
  • 2021-12-16
  • 2019-04-29
  • 1970-01-01
  • 2020-03-06
  • 2013-12-04
相关资源
最近更新 更多